Introduction

packet_parser is a Rust library that turns the bytes of a captured frame into a typed structure, layer by layer, or into a typed error when the bytes are not coherent. This book describes what the crate decodes, how it decides, and what it leaves out.
What the crate does
- Four layers.
parsetakes a frame and its LINKTYPE and returns aPacketFlow: the data link, internet, transport and application layers. - Zero-copy.
PacketFlowborrows the input buffer. No payload is copied. - Fail-closed on the link layer. The LINKTYPE is given by the caller, never guessed from the bytes. An unsupported LINKTYPE is an error.
- Fail-soft above it. An unknown or malformed upper layer does not fail the parse. The layer stays
None, and a recognized but invalid layer is reported incorrupted. - One protocol at a time. Every protocol struct implements
TryFrom<&[u8]>: a transport payload can go straight toTlsPacket::try_from,DnsPacket::try_fromorNtpPacket::try_from. - Typed errors. Each layer and each protocol has its own error type, built with
thiserror. - Designed not to panic on hostile bytes. Every index follows an explicit length check, clippy lints flag
unwrap,expectandpanic!, and the parsers are fuzzed every night. This is a discipline backed by tooling, not a proof: the validation chapter says what is and is not guaranteed. - Tunnels. CAPWAP, GRE, IP-in-IP, VXLAN, Geneve and GTP-U are peeled, and the inner packet is parsed recursively.
Who this book is for
| Reader | Question | Where to start |
|---|---|---|
| Someone who integrates the crate | What does parse return, and what can be built on it? | Getting started, then the PacketFlow struct, the Protocols index and the Limits |
| Someone who audits it | How is a label chosen, and how far is each decoder verified? | Data validation procedure, the dispatch table of the Application chapter, then the "Oracle" and "What is left out" sections of the protocol pages |
| Someone whose protocol the crate does not decode | How can it still get a name, without forking the crate? | Custom parsers and rules |
| Someone who contributes to it | Where does a new protocol go, and what must it prove? | Adding a new protocol, after the Data validation procedure |
What the book guarantees
- A pinned version. The book describes
packet_parser13.3.0 (crates.io, tagv13.3.0in the repository). When the crate moves, the book is updated with it and this line changes. - Tested examples. A snippet marked tested is compiled and run against that version by the
examples/crate of the book, on every change. - Oracles. The counts the book quotes come from the golden tests of the crate, many of which compare each decoded field with tshark on real captures. The Protocols index gives the size of each oracle.
The excerpts of the crate's internals are not compiled: they are quoted from the pinned revision.
How the book is organized
- Getting started covers the public API.
- The
PacketFlowstruct shows what a parsed packet looks like, and the data validation procedure how every struct is built. - The layers follow, from the bottom: data link, internet, transport, application, each with one page per protocol.
- Protocols is the index of every label, and Tunnels covers encapsulation.
- Limits says what a stateless parser cannot see, Adding a new protocol is the contributor's path, and Custom parsers and rules the caller's, for a protocol that stays out of the crate.
- The Glossary defines the words the book relies on.
Getting started
This chapter shows how to use the crate. The rest of the book shows how it is built.
Reference version:
packet_parser13.3.0. Every code snippet marked tested below is included verbatim from the book'sexamples/crate, which compiles and runs against that exact version (cd examples && cargo test). Older versions differ: seeMIGRATION-13.md,MIGRATION-12.mdandMIGRATION-11.mdin the crate repository.
Installation
[dependencies]
packet_parser = "13.3.0"
hex = "0.4" # only for the examples below, to decode hex dumps
Parse one packet
parse is the entry point. It takes two things:
- the LINKTYPE of the capture: the value stored in the PCAP/PCAPNG file (
LinkType::ETHERNET,LinkType::LINUX_SLL, ...); - exactly one packet, without any PCAP record header.
use packet_parser::{LinkType, parse}; fn main() -> Result<(), Box<dyn std::error::Error>> { let raw = hex::decode( "feaa81e86d1efeaa818ec864080045500034000000003d06206b36e6700d\ ac140a0201bbc1087d7f02aa4e2b998e80100081748300000101080a9373\ c9c207ef14e3", )?; // Always pass the LINKTYPE the capture declares. let flow = parse(LinkType::ETHERNET, &raw)?; println!("L2: {}", flow.data_link); if let Some(internet) = &flow.internet { println!("L3: {} {:?} -> {:?}", internet.protocol_name, internet.source, internet.destination); } if let Some(transport) = &flow.transport { println!("L4: {:?} {:?} -> {:?}", transport.protocol, transport.source_port, transport.destination_port); } if let Some(application) = &flow.application { println!("L7: {}", application.protocol); } Ok(()) }
Output:
L2:
Destination MAC: fe:aa:81:e8:6d:1e,
Source MAC: fe:aa:81:8e:c8:64,
Ethertype: IPv4,
VLAN: None,
Payload Length: 52
L3: IPv4 Some(54.230.112.13) -> Some(172.20.10.2)
L4: Tcp Some(443) -> Some(49416)
No L7 line: this segment is a pure ACK with an empty payload, so there is nothing to classify and application stays None.
The same frame, as the book's example crate checks it (tested):
#![allow(unused)] fn main() { #[test] fn parse_a_valid_ethernet_frame() -> Result<(), Box<dyn std::error::Error>> { let raw = hex::decode(ETHERNET_IPV4_TCP_ACK_HEX)?; // Always pass the LINKTYPE the capture declares. let flow = parse(LinkType::ETHERNET, &raw)?; let internet = flow.internet.as_ref().expect("IPv4 announced by the EtherType"); assert_eq!(internet.protocol_name, "IPv4"); assert_eq!(internet.source.unwrap().to_string(), "54.230.112.13"); assert_eq!(internet.destination.unwrap().to_string(), "172.20.10.2"); let transport = flow.transport.as_ref().expect("TCP announced by the IP header"); assert_eq!(transport.source_port, Some(443)); assert_eq!(transport.destination_port, Some(49416)); // A pure ACK: the payload is empty, so there is nothing to classify. assert!(flow.application.is_none()); assert!(flow.corrupted.is_none()); Ok(()) } }
Never guess the LINKTYPE
parse is fail-closed on the link layer: the LINKTYPE comes from the caller and is never guessed from the bytes. Check it up front to reject a whole capture before reading a single packet:
#![allow(unused)] fn main() { use packet_parser::{LinkType, is_supported, parse}; let link_type = LinkType::ETHERNET; if !is_supported(link_type) { return Err(format!("unsupported LINKTYPE {}", link_type).into()); } let flow = parse(link_type, packet_bytes)?; }
| LINKTYPE | Value | Decoder status |
|---|---|---|
| BSD loopback (NULL) | 0 | Supported: four address-family bytes, then the IP packet (11.2.0) |
| Ethernet | 1 | Supported (802.1Q and 802.1ad/QinQ tags included) |
| RAW IP | 101 | Supported for IPv4 and IPv6 |
| Native IEEE 802.11 | 105 | Modelled for CAPWAP inner flows; top-level decoder not yet supported |
| Linux SLL v1 | 113 | Supported |
| Bluetooth H4 with pseudo-header | 201 | Identified, explicitly unsupported |
| IPv4 raw | 228 | Supported |
| IPv6 raw | 229 | Supported |
| IEEE 802.3br mPacket | 274 | Supported for express mPackets (SMD-E); preemptible fragments are refused |
| Linux SLL v2 | 276 | Supported |
| Any other value | Preserved as-is | ParseError::UnsupportedLinkType |
PacketFlow::try_from(&[u8]) and DataLink::try_from(&[u8]) still exist. They take a bare byte slice and assume Ethernet. Feeding them a Linux any capture (LINKTYPE_LINUX_SLL) does not fail: the 16 cooked-header bytes are read as MAC addresses and an EtherType, and you get Ok with fabricated addresses. Use them only when the capture is known to be Ethernet.
Reading the outcome
Only the link layer can fail the parse. Above it, three outcomes are distinct and must not be confused:
flow.internet / transport | flow.corrupted | Meaning |
|---|---|---|
Some(..) | None | The layer was recognized and decoded. |
None | None | The protocol is not supported (e.g. the experimental EtherType 0x88B5), nothing above it can be reached. |
None | Some(..) | The layer was recognized (by its EtherType or IP protocol number) but its bytes are invalid. CorruptedLayer::layer says which one, error says why: since 13.0.0 the decoder's error, typed. |
Some(..) | Some(..) | Semantic anomaly: the header is readable but no conforming stack emits it (TCP SYN+FIN, reserved bits set). The layer is kept so its ports remain available for flow correlation; nothing is parsed above it. |
The four shapes side by side, on the frames of the tests below (the anomaly is a TCP segment with SYN and FIN both set), and the Err only the link layer returns. A dark row is None: the difference between not supported and corrupted is only the corrupted row.
A recognized layer with invalid bytes (tested):
#![allow(unused)] fn main() { #[test] fn a_recognized_but_invalid_upper_layer_is_reported_not_fatal() { let raw = hex::decode(ETHERNET_IPV4_TCP_ACK_HEX).unwrap(); // Cut 6 bytes into the IPv4 header: the EtherType still says IPv4, // so the layer is recognized, but its bytes are invalid. let flow = parse(LinkType::ETHERNET, &raw[..20]).unwrap(); assert!(flow.data_link.as_ethernet().is_some()); // kept assert!(flow.internet.is_none()); let corrupted = flow.corrupted.expect("recognized layer with invalid bytes"); assert_eq!(corrupted.layer, CorruptedLayerKind::Internet); // Since 13.0.0 `error` is the decoder's error, typed: a `match` // sorts the causes. Its `Display` is the text of 12.x. assert!(matches!( corrupted.error, CorruptedLayerError::Internet(InternetError::Ipv4Error(Ipv4Error::InvalidLength { expected: 20, actual: 6, })) )); assert_eq!( corrupted.error.to_string(), "IPv4 error: Invalid IPv4 packet length: expected at least 20 bytes, got 6 bytes" ); } }
An unsupported protocol above the link layer, which is not corruption (tested):
#![allow(unused)] fn main() { #[test] fn an_unsupported_upper_layer_leaves_the_layer_none_without_corruption() { // Synthetic frame: two MAC addresses, EtherType 0x88B5 (the IEEE 802 // local experimental EtherType, decoded by no one) and a few payload // bytes. let mut raw = hex::decode("0180c200000e001122334455").unwrap(); raw.extend_from_slice(&[0x88, 0xb5, 0x02, 0x07, 0x04, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55]); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); // Not supported is not the same as corrupt: nothing above the link // layer could be reached, and nothing is reported as invalid. assert!(flow.internet.is_none()); assert!(flow.transport.is_none()); assert!(flow.application.is_none()); assert!(flow.corrupted.is_none()); } }
And the two link-layer failures, the only ones that return Err (tested):
#![allow(unused)] fn main() { #[test] fn an_unsupported_linktype_is_refused_before_reading_bytes() { let raw = hex::decode(ETHERNET_IPV4_TCP_ACK_HEX).unwrap(); let bluetooth = LinkType::BLUETOOTH_HCI_H4_WITH_PHDR; assert!(!is_supported(bluetooth)); assert!(matches!( parse(bluetooth, &raw), Err(ParseError::UnsupportedLinkType(LinkType(201))) )); } }
#![allow(unused)] fn main() { #[test] fn a_truncated_link_header_fails_the_parse() { let raw = hex::decode(ETHERNET_IPV4_TCP_ACK_HEX).unwrap(); // Only the link layer can fail the parse: 10 bytes cannot hold the // 14-byte Ethernet header. let error = parse(LinkType::ETHERNET, &raw[..10]).unwrap_err(); assert_eq!( error.to_string(), "Invalid link layer: LINKTYPE 1 packet is truncated: required bytes 14, actual bytes 10" ); } }
Main API
| Need | API |
|---|---|
| Check whether a link decoder exists | is_supported(LinkType) |
| Parse a packet (canonical) | parse(LinkType, &[u8]) |
| Parse with caller-declared ports ("Decode As") | parse_with(LinkType, &[u8], &ParseConfig) |
| Parse Ethernet, compat shortcut (assumes Ethernet) | PacketFlow::try_from(&[u8]) |
| Parse only Ethernet/VLAN (assumes Ethernet) | DataLink::try_from(&[u8]) |
| Parse only L3 | Internet::try_from_network_parts(NetworkProtocol, &[u8]) |
| Parse only L4 | Transport::try_from_parts(Option<TransportProtocol>, &[u8]) |
| Parse one application protocol in detail | packet_parser::parse::application::protocols::<proto>::XxxPacket::try_from(&[u8]) |
| Detach the result from the original buffer | flow.to_owned_flow() |
| Iterate over encapsulated flows | flow.flatten() |
| Verify a checksum (opt-in) | packet_parser::checksum::verify_{ipv4_header,tcp,udp}_checksum |
| Measure the time spent per layer | parse_timed(...) with the parse_timing feature |
"Decode As": an FTP server on port 2121
Some protocols are only detected when the port and the content agree (see the application chapter). ParseConfig lets the caller declare extra ports, for the 30 protocols of DecodeAsProtocol (the list); since 12.1.0, DecodeAsProtocol::ALL is that list, for a caller that offers the choice. The port never replaces the content check: it only gives the probe its chance before the rest of the table.
#![allow(unused)] fn main() { use packet_parser::{DecodeAsProtocol, LinkType, ParseConfig, parse_with}; let config = ParseConfig::new().decode_as(2121, DecodeAsProtocol::Ftp); let flow = parse_with(LinkType::ETHERNET, &raw, &config)?; }
Owned flows and serialization
PacketFlow<'a> borrows the input buffer: it cannot outlive it. To store a flow, send it across threads or keep it after the capture buffer is reused, convert it with to_owned_flow(). The conversion is lossy on purpose: the owned form drops the payloads and the per-layer details, and keeps the flow identity (addresses, protocols, ports).
What PacketFlowOwned keeps, layer by layer:
| Field | Owned type | Kept |
|---|---|---|
data_link | LinkLayerOwned | the LINKTYPE, the NetworkProtocol, and the fields of the format's view: MACs, EtherType and VLAN stack for Ethernet, the cooked-header fields for SLL and SLL2, the 802.11 addresses |
internet | InternetOwned | both addresses, their IpType, the protocol name as a String |
transport | TransportOwned | both ports, the protocol as its display name ("TCP"), not the typed TransportProtocol |
application | ApplicationOwned | the label, as a String |
inner, corrupted | Box<PacketFlowOwned>, CorruptedLayer | both, inner converted recursively |
Dropped: every payload, every details, Internet::payload_protocol, and the PPPoE session of an Ethernet frame (DataLink::pppoe, since 11.6.0). Every owned type derives PartialEq, Eq and Hash over what it keeps, which makes PacketFlowOwned usable as the key of a flow table. That key is coarser than the borrowed identity: without the session, two PPPoE sessions that agree on everything else are one owned flow (PPPoE session).
PacketFlow and PacketFlowOwned both implement serde::Serialize and produce the same JSON text: since 11.7.0 (#193), the borrowed model writes its members in the order of the owned one, so the two strings are equal byte for byte. Before that, the keys and the values were already the same, but the borrowed model wrote protocol_transport before the ports and ethertype after the VLAN tags. The link layer is nested and tagged, the upper layers are flattened, payloads and details are not serialized.
{
"data_link": {
"link_type": 1,
"network_protocol": { "kind": "ipv4" },
"link_kind": "ethernet",
"link_details": {
"destination_mac": "fe:aa:81:e8:6d:1e",
"source_mac": "fe:aa:81:8e:c8:64",
"ethertype": "IPv4"
}
},
"source_ip": "54.230.112.13",
"ip_source_type": "Public",
"destination_ip": "172.20.10.2",
"ip_destination_type": "Private",
"protocol_internet": "IPv4",
"source_port": 443,
"destination_port": 49416,
"protocol_transport": "TCP"
}
The owned form is what you keep once the capture buffer is gone, and its text is the borrowed one (tested):
#![allow(unused)] fn main() { #[test] fn owned_flows_serialize_like_borrowed_ones() -> Result<(), Box<dyn std::error::Error>> { let raw = hex::decode(ETHERNET_IPV4_TCP_ACK_HEX)?; let flow = parse(LinkType::ETHERNET, &raw)?; let borrowed_json = serde_json::to_string(&flow)?; // The owned form outlives the buffer; it drops payloads and details. let owned = flow.to_owned_flow(); drop(raw); // Since 11.7.0, both models write the same text, members in the same order. let owned_json = serde_json::to_string(&owned)?; assert_eq!(owned_json, borrowed_json); let json: serde_json::Value = serde_json::from_str(&owned_json)?; assert_eq!(json["data_link"]["link_type"], 1); assert_eq!(json["data_link"]["link_kind"], "ethernet"); assert_eq!(json["source_ip"], "54.230.112.13"); assert_eq!(json["protocol_transport"], "TCP"); assert_eq!(json["destination_port"], 49416); Ok(()) } }
Timing (benchmarks)
parse_timed runs the exact same pipeline as parse and reports the nanoseconds spent in each layer. The API is always there; without the parse_timing feature nothing is measured and ParseTiming stays zeroed, so enabling the feature anywhere in a dependency graph never changes a signature.
#![allow(unused)] fn main() { use packet_parser::{LinkType, parse_timed, timing::ParseTiming}; let mut timing = ParseTiming::default(); let flow = parse_timed(LinkType::ETHERNET, &raw, &mut timing)?; println!("L2={}ns L3={}ns L4={}ns L7={}ns total={}ns", timing.l2_ns, timing.l3_ns, timing.l4_ns, timing.l7_ns, timing.total_ns); }
cargo test --features parse_timing
What each counter covers (see the engine):
l2_ns: the link decoder. Choosing it (decoder_for) is not counted.l3_nsandl4_ns: the internet and transport stages.l7_ns: tunnel detection, the dispatch table and STP, and the whole parse of every inner flow: on a VXLAN packet, the inner Ethernet, IP and TCP are counted in the outerl7_ns. It stays at 0 for an anomalous TCP segment, which leaves before L7.total_ns: the whole call.
Measuring does not change the path: the pipeline is written once, over a TimingSink that does nothing for parse and reads the clock for parse_timed. parse_timed takes no ParseConfig, so a timed parse has no Decode As ports.
Known limitations
The parser is stateless: it sees one packet at a time, reassembles nothing, verifies no checksum and decrypts nothing. The application layer is a label, not a decode. The Limits page lists what follows from each of these, and what the crate exposes to detect it; the Protocols page lists every label. A protocol the crate does not decode can still be named by a parser of the caller (Custom parsers and rules).
PacketFlow struct
parse takes the bytes of a packet and returns a PacketFlow. This page shows what the bytes hold, what the struct keeps of them, and the order in which the engine fills it.
A packet is a list of bytes
The crate receives a packet as a slice:
#![allow(unused)] fn main() { let packet: &[u8] = &[0x02, 0x42, 0xc0, 0xa8, 0x00, 0x01, /* 65 more bytes */]; }
The parsed structures borrow that slice and never copy it. Every one of them carries a lifetime 'a tied to the input buffer.
Layers in the bytes
Each protocol occupies one part of the packet:
The parts are nested. Each layer carries the next one as its payload:
The struct
A parsed packet has four layers:
The data link layer is always present. The others depend on the packet.
#![allow(unused)] fn main() { pub struct PacketFlow<'a> { /// Link layer (mandatory), tagged with its canonical LINKTYPE. pub data_link: LinkLayer<'a>, /// Internet layer (optional). pub internet: Option<Internet<'a>>, /// Transport layer (optional). pub transport: Option<Transport<'a>>, /// Application layer (optional, best-effort). pub application: Option<Application>, /// Encapsulated packet, when this flow is a tunnel (CAPWAP, GRE, VXLAN...). pub inner: Option<Box<PacketFlow<'a>>>, /// Present when a recognized layer carried invalid bytes. pub corrupted: Option<CorruptedLayer>, } }
Two fields are not layers:
inner. Some packets carry a whole other packet in their payload. When a tunnel is recognized, its name goes intoapplicationand the encapsulated packet is parsed recursively intoinner(Tunnels).corrupted. A layer that was recognized (the EtherType said IPv4, the IP header said TCP) but whose bytes are invalid does not fail the parse. The lower layers are kept, that layer and the ones it would have carried stayNone, and the problem is reported here (Getting started).
Flow identity
Each layer holds a source and a destination:
The flow identity is that set: MAC addresses, IP addresses, protocols, ports. PacketFlow implements PartialEq, Eq and Hash on the identity only, not on the raw bytes. Two packets of one conversation that carry different data compare equal and hash identically, which is what a flow table needs: a HashMap<PacketFlowOwned, Stats>. Since 11.6.0 the identity of an Ethernet frame also holds the session and the PPP protocol of a PPPoE session, which the owned form does not keep (PPPoE session).
The structs behind each layer
Each layer exposes two levels of information:
- the flattened summary of the diagram (
source,destination,protocol_name,source_port...), which is the identity of the layer and what is serialized; - a
detailsfield (InternetDetails,TransportDetails) with the full parsed header (Ipv4Packet,TcpPacket,IcmpPacket...). The TTL, the DSCP or the TCP flags are read there, without parsing the payload again. Equality, hashing and serialization ignoredetails.
The data link layer is the exception. LinkLayer is format-neutral (Ethernet, RAW IP, Linux cooked capture...), and the view of one format is reached through as_ethernet(), as_linux_sll() and the like (Data link).
Each layer announces the next
Each layer is parsed from the payload of the one below, and each layer says what the next one is:
| Step | Input | What names the next protocol | Output |
|---|---|---|---|
| Link | LINKTYPE + packet bytes | the caller (LINKTYPE) | LinkLayer + NetworkProtocol + L3 payload |
| Internet | NetworkProtocol + L3 payload | EtherType / SLL protocol field | Internet + payload_protocol + L4 payload |
| Transport | TransportProtocol + L4 payload | IP protocol number / next header | Transport + ports + L7 payload |
| Application | Transport (ports + payload) | content probes, guarded by transport and sometimes by port | Application { protocol } |
The engine, end to end
The table gives the principle. Here is how parse chains it:
Everything above DecodedLink depends on the capture format, and is the only part that can return Err (data link chapter). Everything below it is one pipeline, shared by every LINKTYPE and by every tunnel level. It is a single function, parse_decoded_into, quoted here with its comments removed:
#![allow(unused)] fn main() { let (data_link, network_protocol, network_payload) = decoded.into_parts(); let (internet, l3_corruption) = sink.time(Stage::L3, || { Self::parse_l3(network_protocol, network_payload) }); let (transport, l4_corruption) = sink.time(Stage::L4, || Self::parse_l4(internet.as_ref())); let transport = match transport { Some(transport) if transport.is_anomalous_tcp() => { return Ok(Self::anomalous_tcp_flow(data_link, internet, transport, l3_corruption)); } transport => transport, }; let (application, inner) = sink.time(Stage::L7, || { let (application, inner) = Self::parse_l7_and_inner(internet.as_ref(), transport.as_ref(), depth, decode_as); (application.or_else(|| Self::detect_stp(&data_link)), inner) }); Ok(PacketFlow { data_link, internet, transport, application, inner, corrupted: l3_corruption.or(l4_corruption), }) }
Read from top to bottom:
- Each stage turns its error into data.
parse_l3andparse_l4mapUnsupportedProtocoltoNoneand every other error to aCorruptedLayer. Since 13.0.0 itserroris the error itself, typed,CorruptedLayerError::InternetorCorruptedLayerError::Transport; until 12.x it was the error'sDisplay, aString(#275). Building it no longer allocates: an IPv4 total length past the frame costs 106 ns instead of 365, about the cost of a sound ACK. A layer that isNoneleaves nothing for the next one, socorruptedholds at most one report:l3_corruption.or(l4_corruption)is the first failure, and the only one. - An anomalous TCP segment leaves before L7, in a
#[cold]function: transport kept, anomaly reported, no application. Weaving that case into the common stages cost about 10 ns on every TCP segment (transport chapter). - L7 has a fixed order. First an IP-level tunnel (GRE, IP-in-IP), then a UDP tunnel (CAPWAP, VXLAN, Geneve, GTP-U), then the dispatch table, Decode As ports first. STP comes last, from the link layer, and only when nothing gave a label: a BPDU has no network layer to reach the table.
- A tunnel re-enters at
DecodedLink, one level deeper, with the same Decode As ports (tunnels chapter). That recursion runs inside the L7 stage, which is where its time is counted. sinkis the timing: a no-op forparse, a clock forparse_timed, so the measured path is the parsed path (getting started).
The port never decides alone
Up to the transport layer, a field names the next protocol: the EtherType, then the IP protocol number. Above it, nothing does. A port number is a convention, which a scanner, a relay or an administrator can break, so port 80 does not make a payload HTTP.
The application label therefore comes from the content. Where the content is enough, a rule of the dispatch reads it on any port. Where it is not, the port is added as a guard: an FTP reply, an SMTP reply and an NNTP reply are the same bytes (220 text CRLF), and each is labelled only on its own port. In both cases the content must match. The Application chapter has the table of these rules.
Data validation procedure
Every struct of the crate is built by a TryFrom that applies its validation steps to the bytes. When they all pass, it returns the typed structure. When one fails, it returns a typed error, defined with the thiserror crate.
The top-level API returns ParseError; each layer and each protocol has its own error type (DataLinkError, Ipv4Error, TcpError, NtpPacketParseError...).
Every struct is a TryFrom<&[u8]>
This is the one rule of the crate. DataLink, Ipv4Packet, TcpPacket, DnsPacket, TlsPacket... all of them are built the same way:
#![allow(unused)] fn main() { impl<'a> TryFrom<&'a [u8]> for Ipv4Packet<'a> { type Error = Ipv4Error; fn try_from(data: &'a [u8]) -> Result<Self, Self::Error> { validate_ipv4_min_length(data)?; let version_ihl = data[0]; validate_ipv4_version(version_ihl >> 4)?; let header_len = ((version_ihl & 0x0F) as usize) * 4; validate_ipv4_header_length(header_len)?; validate_ipv4_header_available(data.len(), header_len)?; let total_length = u16::from_be_bytes([data[2], data[3]]); validate_ipv4_total_length(total_length, header_len, data.len())?; // ... every remaining field is read with from_be_bytes ... // 0 is accepted: before TCP segmentation offload, the stack leaves the // total length to the network card, and the payload runs to the end of the frame. let end = if total_length == 0 { data.len() } else { usize::from(total_length) }; Ok(Ipv4Packet { /* ... */, payload: &data[header_len..end] }) } } }
The TryFrom is a linear sequence, in wire order:
- a pre-check on the length, so that every index below is proven in-bounds;
- one check per constrained field, chained with
?: check the bytes of the field, place the value if it is valid, move on to the next field; - cross-field validations between values already extracted;
- build the struct with the validated values, and split header from payload.
As soon as a check fails, ? returns the typed error: the bytes are not this protocol.
Where the checks live
The parser file only chains the calls. The checks themselves live in a separate, crate-internal module, one file per protocol:
src/
parse/ the TryFrom impls and the structs (public)
checks/ validate_* and extract_* functions (crate-internal)
errors/ one thiserror enum per protocol (public)
Two forms of functions:
extract_*: verifies the bytes of one field and returns the typed value, ready to be placed in the struct (extract_stratum,extract_reference_idon the NTP side);validate_*: returnsResult<(), Error>for controls that produce no value: length pre-check, cross-field coherence (validate_ipv4_total_length,validate_datetime_ordering).
A field without any constraint (a raw counter, a free identifier) is read directly with from_be_bytes in the parser.
Typed errors
Errors carry the values that failed, never a bare string, so a consumer can match on them:
#![allow(unused)] fn main() { #[derive(Error, Debug)] #[non_exhaustive] pub enum TcpError { #[error("Packet too short to be a valid TCP header")] PacketTooShort, #[error("Invalid data offset: {0}")] InvalidDataOffset(u8), #[error("Invalid TCP flags {flags:#04x}: SYN and FIN are both set")] InvalidFlags { flags: u8 }, #[error("TCP reserved bits are set: {bits:#05b}")] ReservedBitsSet { bits: u8 }, } }
Errors nest with #[from]: Ipv4Error converts into InternetError, which converts into ParseError. Every error enum is #[non_exhaustive], so a new variant can be added in a minor version; a match on them needs a _ arm.
Structural corruption vs. semantic anomaly
Not every failed check means the same thing:
- structural: the bytes cannot be read as this protocol (truncated header, impossible length). The
TryFromreturnsErr, and in the pipeline the layer becomesNonewithcorrupted: Some(..); - semantic: the header reads fine but says something no conforming stack emits (TCP SYN+FIN, reserved bits set). The
TryFromreturnsOk; the anomaly is exposed byTcpPacket::anomaly(), and the pipeline keeps the layer while reporting it incorrupted. This is a classic scan signature: the ports must stay available for correlation.
Fail-closed below, fail-soft above
The two error paths of PacketFlow are asymmetric on purpose:
- the link layer is fail-closed: an unsupported LINKTYPE or a truncated link header returns
Err(ParseError). Without a valid link layer there is nothing trustworthy to build on; - everything above is fail-soft: an unsupported protocol leaves the layer
None, a corrupt one is reported incorrupted. Real-world traffic is full of protocols the crate does not decode, and a flow matrix must not lose the L2/L3 information because of an odd L4.
No panic on hostile bytes
A parser of hostile bytes must never bring its host down. What the crate does about it, precisely:
-
Lints.
lib.rsenablesclippy::unwrap_used,clippy::expect_usedandclippy::panicas warnings outside of tests, and the CI runs clippy with-D warnings, which makes them blocking. The rare justified sites carry a motivated#[expect]. Test code is free tounwrap. -
Truncating casts. 12.1.0 adds
clippy::cast_possible_truncationto these lints (#273): a number read from the wire is no longer narrowed withas, it goes throughFromortry_from. The lint found a defect in QUIC. Two lengths read from a varint, Token Length and Length, were cut fromu64tousize. On a 32-bit target a value of 232 or more lost its high bits, and the decoder read fewer bytes than the packet announced instead of refusing it. Both now saturate, and the bounds check refuses them (Truncated,PayloadTooShort); nothing changes on 64 bits. Of the 32 other casts found, five keep a motivated#[expect]: the IPv4 pseudo-header, two ASTERIX FRNs, the DNP3 CRC table and the nanoseconds of GOOSE. -
The indexing idiom.
data[0]aftervalidate_ipv4_min_length(data)is the pattern everywhere: index after an explicit length check. The lintsindexing_slicingandarithmetic_side_effectsare deliberately not enabled: with more than a thousand such accesses, they would flag every one of them. -
Fuzzing. The absence of panic on these accesses is exercised by the fuzz targets under
fuzz/, the 46[[bin]]entries offuzz/Cargo.toml. Each one feeds hostile bytes to an entry point and, beyond the absence of panic, most check what an accepted input must satisfy:parse_packetflow:PacketFlow::try_from, thenparse_withwith one Decode As port: the first byte chooses the protocol inDecodeAsProtocol::ALL, the next two are the port; nothing else is checked, the policies arepolicy_dispatch's;parse_dns:DnsPacket::try_from, name compression included: hostile pointers must create neither a loop nor a panic;parse_application:classify_payload. Five leading bytes choose the transport and the two ports, the rest is the payload, so every probe of the table is reached, port rules included, and must reject hostile bytes cleanly; one input in two is also classified with no port. On TCP or UDP with its ports, the label must be the oneparsegives the Ethernet/IPv4 frame built around the same payload;parse_linktype:parsewith a LINKTYPE chosen by the first byte among all thoseis_supportedannounces, plusu32::MAXand the byte itself, thento_owned_flowandflatten;parse_quic:QuicPacket::try_from, the Long Header: varints, Connection IDs and the Length field; since 13.1.0 also the Version Negotiation, version 0 then versions of 4 bytes to the end of the input;parse_s7comm:S7CommPacket::try_from: an accepted packet satisfies the TPKT + COTP-DT + S7 invariants, lengths included;parse_cotp:CotpHeader::from_bytesandCotpHeader::try_from: the two entry points agree, and LI, TPDU type and exposed fields are consistent;parse_giop:find_giop_messageandgiop_messages: CDR cursor, IORs and IIOP profiles, resynchronization; no message covers more bytes than the buffer;parse_asterix:AsterixPacket::try_fromover the eleven categories: the data blocks tile the input, every item points into it, and every typed decoder is run on every record;parse_ptp:PtpPacket::try_fromandtry_from_udp: message, TLVs and trailing bytes tile the input, and the UDP form accepts a subset of the layer 2 one;parse_profinet:validate_frameandProfinetPacket::try_from: DCP is decoded only for DCP Frame IDs, and its blocks and NameOfStation point into the buffer;parse_rtps:RtpsPacket::try_from: the submessages tile the message and borrow from the input; since 13.0.0 it also callsinline_qos(),serialized_payload()anddiscovery()on every submessage: each decoded ParameterList, its values and the serialized data point into the body of the submessage, the parameters tile their list, and every typed accessor reads without a panic, with three DDS frames of the corpus added to its mutation seeds;parse_stanag5066:SisPdu::try_fromon chained S_PDUs:consumedstays within the input, the U_PDU borrows from it, and a cut S_PDU is the last one, running to the end of the input;parse_dis:DisPacket::try_fromandtry_from_lenient: the PDUs, then the trailing bytes of the lenient reading, tile the input, and the strict reading accepts exactly the lenient readings that leave no trailing bytes;parse_ipsec:IkePacket::try_from,IkePacket::from_udp,UdpEncapsulation::classifyandEspPacket::try_from: the payloads tile the message, and the demultiplexing of UDP 4500 is a partition;parse_dnp3:Dnp3Packet::try_from: the link frames tile the input, and any single-byte change of a real seed is rejected, the CRCs being what makes the blind probe safe; since 11.7.0 it also mutates the user data alone and recomputes the CRCs, so that its mutations reach the transport and application layers and the object headers;parse_radius:RadiusPacket::try_from: the attributes tile the packet, whose declared length is the input's;parse_rdp:RdpPacket::try_from: the TPKTs tile the segment, the last one possibly cut;parse_iec104:Iec104Packet::try_from: the APDUs tile the segment, the last one possibly cut, and an ASDU in sequence numbers its objects one after the other;parse_bacnet:BacnetPacket::try_from: the BVLC length is the input's, and every borrow points into it;parse_goose:GoosePacket::try_from: the length is the input's, and the number of allData elements is bounded by it;parse_lldp:LldpPacket::try_from: the TLVs and the padding tile the input, and the blind probe ofInternet::try_fromnever accepts an LLDPDU the decoder refuses;parse_valmet_dna:ValmetDnaPacket::try_fromandTimeBeacon::try_from: the declared length is the input's minus two, the tag and the body borrow from the input, the clocks are within their ranges, andclassify_payload, on UDP and with no port, says"Valmet DNA"exactly when the message family is known;parse_wireguard:WireGuardPacket::try_from: the size is the one of the type, a keepalive is exactly 32 bytes, and what the blind cascade labels WireGuard has null reserved bytes;policy_dispatch: the oracles of the dispatch policy, moved out ofparse_packetflowby #108: FTP, SMTP and NNTP off their ports, S7Comm, COTP and Decode As, throughPacketFlow::try_fromandparse_with; its text oracle is shared withtests/fuzz_policy_parity.rs, which compares it with the dispatch table on every pull request.
12.1.0 adds fourteen targets, one per application decoder (#272). Nineteen decoders were reached only through the dispatch, by
parse_application,parse_packetflowandpolicy_dispatch; measured on them, line coverage went from 77.9 % to 94.3 %. Each target also calls what the dispatch never calls: iterators, on-demand bodies,Display.parse_dhcpv6:Dhcpv6Packet::try_from: message type and transaction ID are those of the wire, and the options are the input without its first four bytes;parse_ethernet_ip:EtherNetIpPacket::try_from: the declared length is the input's, the items of the Common Packet Format tile the command data, and the iterator,lenandgetagree;parse_http:HttpRequest::try_fromandHttpResponse::try_from: method, URI, version and headers borrow from the input, the body is its end, the header iterator agrees withlen,is_emptyandget, andparse_http_requestandparse_http_responsegive the verdict oftry_from;parse_mqtt:MqttPacket::try_from, 3.1.1 and 5: the variable header and the payload of the first packet add up to its Remaining Length and point into the input;parse_netbios:NbnsPacket::try_fromandNbssPacket::try_from: the NBNS counts are the lengths of its vectors, every borrow points into the input, and the NBSS payload has the declared length;parse_ntp:NtpPacket::try_from: the fields are those of the wire, and the reference has the form its stratum imposes;parse_opcua:OpcuaPacket::try_from: the chunks the iterator returns tile the input, only the last one may be cut or be followed by 1 to 7 bytes, the start of the next header, which must start one of the seven message types and, from the fourth byte, a chunk type (13.1.1, #333), every borrow points into the input, andlenandgetagree with the iterator;parse_openvpn:OpenVpnPacket::try_fromandfrom_tcp_stream: opcode and key_id are those of the first byte, the payload is what follows the header of its opcode, and the TCP form returns the declared record, then the rest of the stream;parse_postgresql:PostgreSqlPacket::try_from: the typed messages tile the input, every declared length is the one of its payload, and every borrow points into the input;parse_snmp:SnmpPacket::try_from, v1, v2c and v3: the message has the form of its version, the PDU the form of its type, and every borrow points into the input;parse_srvloc:SrvlocPacket::try_from, SLP v1 and v2: the declared length is the input's, every borrow points into it, andbody()returns the form the function announces or an error. Its seeds are synthetic: the repository has no SLP capture;parse_ssdp:SsdpPacket::try_from: every header value borrows from the input, and a search always carries its MAN;parse_tls:TlsPacket::try_from,looks_like_tlsandparse_tls_records:looks_like_tlsgives the verdict oftry_from, the list of records is empty exactly when the first one does not decode, and the records follow one another from the start of the input, each with the type, version and length of its header;parse_umas:UmasPacket::try_fromandMBAP::try_from: the Modbus function code is0x5A, session and UMAS function are the first two bytes of the PDU, the data are what follows, and the MBAP also decodes alone.
13.x adds seven targets:
parse_java_rmi:JavaRmiPacket::try_fromon the input and on seven frames of the JDK capture altered by the input: the type is the first byte and every field the one of the wire, what follows a stream header, the arguments and the value end the input, the hostname points into it, andis_self_identifyingholds exactly for a stream header, a Call or a Return;parse_rules:RuleSet::from_tomlon any text, which is accepted or refused but never panics; an accepted file then runs its rules on its own bytes. The same bytes then go, as a TCP and as a UDP payload on a few ports, through the rules of a fixed file, fields included (#325);parse_sip, in 13.2.0:SipMessage::try_fromon the input and on two synthetic messages altered by it, the INVITE of RFC 3261 §24.2 and a 180 Ringing with compact headers, one of them folded: every field points into the input, a status code goes from 100 to 699, every method is inSIP_METHODS, the CSeq of a request names its method with a number below 231, the body ends within the input and within Content-Length, andheaders.getfinds the Via and the Call-ID under their long names;parse_rtp, in 13.3.0:RtpPacket::try_fromon the input and on two frames altered by it, one with an RFC 8285 extension, one with the marker set: every field is the one of the wire, no payload type is in 72 to 76, each borrow points into the input, and the header, the CSRC list, the extension, the payload and the padding tile the datagram;parse_nmf:NmfSegment::try_fromon the input, on the preamble of the censored capture and on the start of one of its envelopes: every record type is at most0x0C, a version is 1.0, each string and payload points into the input, an envelope never holds more than it announces, and nothing follows a truncated one;parse_dcerpc:DceRpcPdu::try_fromon the input, on a Bind and on a Request of the Ultimate PCAP: the header fields are those of the wire, the header, the body and the rest tile the segment, the body never goes past the fragment, a rest exists only behind a whole fragment, and only a Request gives request fields;parse_rtcp:RtcpCompound::try_fromon the input, on a compound datagram and on a feedback packet alone: the packets tile the datagram, every type is 200 to 207, every body is a multiple of four bytes inside the input, only the last packet is padded, and only a Sender Report gives sender information.
The oracle of
parse_opcuashows what the CI of a pull request cannot catch. 13.1.0 let a complete OPC UA chunk be followed by the start of the next header, but the oracle still wanted chunks that tile the whole input. The CI runs each target once (-runs=1), so the nightly run found it, on a mutated seed (#333). The failure showed a gap in the decoder too: below three bytes, the start of the next header was not checked. 13.1.1 fixed the decoder and the oracle together.Five more targets were written, then dropped: those of AMS, Bitcoin, DHCP, Modbus/TCP and SSH reached no line that the generic targets did not.
Most protocol targets also mutate seeds built from real frames of the corpus, named in their comments, so that hostile bytes reach the deep paths from the first run. The nightly workflow,
.github/workflows/fuzz.yml, draws its matrix from these[[bin]]entries, so that a new target runs the very night it is added; it keeps each target's corpus from one night to the next, and a failed night opens or completes afuzz-failureissue. On every pull request, the CI checks that each file offuzz/fuzz_targets/has its[[bin]], builds the targets and runs each one once (-runs=1), which also runs the fixed oracles ofpolicy_dispatch.
None of this is a proof. Lints catch the explicit panics, not an out-of-bounds index; fuzzing finds panics, it does not demonstrate their absence. What the crate can claim is that every parser follows the same length-checked discipline, that the tooling refuses the obvious deviations, and that the fuzzers have not found a panic on the published versions. The same honesty applies to the other properties described in this book: TryFrom and corrupted describe how the supported layers behave; a protocol the crate does not decode is simply None, and zero-copy holds for the L2/L3/L4 structs and for the bytes of most application parsers. Many of them do allocate a Vec for each list whose length the packet dictates (the records of DNS and ASTERIX, the messages of PostgreSQL and Modbus/TCP, the APDUs of IEC 104, the attributes of RADIUS, the TLVs of LLDP...), every pre-allocation bounded first by the bytes left; and two copy bytes: DNS, whose names are Strings, and DNP3, whose user data are rebuilt without their CRCs.
Data link
The data link layer is the first one parse reads, and the only one whose format the bytes do not announce. This page explains how the crate selects the format; each format then has its own page.
The LINKTYPE decides: LinkType and LinkLayer
A capture is not always Ethernet. A capture on the Linux any interface is Linux cooked (SLL), a VPN capture is often RAW IP, an industrial capture can be 802.3br. The bytes of these formats look nothing like an Ethernet header, and nothing in them says which format they are. Only the capture file knows, through its LINKTYPE.
That is why parse takes a LinkType and never guesses. LinkType(pub u32) uses the canonical LINKTYPE_* values stored in PCAP/PCAPNG files, and stays open: an unknown value is preserved, not collapsed into an Unknown variant. parse never reads a capture file, so mapping the capture source to this namespace is the caller's job: a DLT_* value from a live capture must be normalized when it differs from the LINKTYPE_* value, and a PCAPNG reader passes the LINKTYPE of the interface each packet references.
#![allow(unused)] fn main() { /// Single source of truth for the link types backed by a decoder. #[inline(always)] const fn decoder_for(link_type: LinkType) -> Option<DecoderKind> { match link_type { LinkType::ETHERNET => Some(DecoderKind::Ethernet), // BSD loopback: four bytes of address family, then the IP packet. LinkType::NULL => Some(DecoderKind::NullLoopback), // RAW, IPV4 and IPV6 share the same shape: the bytes start directly // at the IP header. RawIpDecoder reads the version from the first // nibble, which covers all three without a dedicated decoder. LinkType::RAW => Some(DecoderKind::RawIp(LinkType::RAW)), LinkType::IPV4 => Some(DecoderKind::RawIp(LinkType::IPV4)), LinkType::IPV6 => Some(DecoderKind::RawIp(LinkType::IPV6)), LinkType::LINUX_SLL => Some(DecoderKind::LinuxSll), LinkType::LINUX_SLL2 => Some(DecoderKind::LinuxSll2), LinkType::IEEE802_3BR => Some(DecoderKind::Ieee8023br), _ => None, } } }
This function is the single source of truth: is_supported is decoder_for(..).is_some(), and parse returns ParseError::UnsupportedLinkType before reading a single byte when it is None. Two constants have no decoder: LinkType::IEEE802_11 (105) and LinkType::BLUETOOTH_HCI_H4_WITH_PHDR (201) are named, and refused like any unknown value.
Every decoder produces the same format-neutral output, consumed by the shared L3/L4/L7 pipeline:
#![allow(unused)] fn main() { #[non_exhaustive] pub struct LinkLayer<'a> { link_type: LinkType, // the LINKTYPE it was decoded as network_protocol: NetworkProtocol, // what comes next: Ipv4, Ipv6, Arp, Profinet, // Ptp, Goose, Lldp, or Other(u16) network_payload: &'a [u8], // the L3 bytes kind: LinkLayerKind<'a>, // the format-specific view } #[non_exhaustive] pub enum LinkLayerKind<'a> { Ethernet(DataLink<'a>), RawIp(RawIpLink<'a>), LinuxSll(LinuxSllLink<'a>), LinuxSll2(LinuxSll2Link<'a>), Ieee80211(Ieee80211Link<'a>), } }
The fields are private and every constructor is format-specific (LinkLayer::ethernet or From<DataLink>, LinkLayer::ieee80211, crate-internal ones for the other decoders), so link_type, network_protocol and kind cannot disagree. LinkLayerKind is #[non_exhaustive]: a new link format is a new variant, and a match on it needs a wildcard arm.
NetworkProtocol is deliberately independent from Ethernet: RAW IP announces Ipv4 or Ipv6 without fabricating an EtherType, while Ethernet and SLL map their protocol field to the same value. Seven values are named, the protocols the internet layer decodes; any other is Other(u16) and gives no internet layer. For a PPPoE session frame carrying IP, the Ethernet view maps the EtherType reached once the session is peeled: an IPv4 packet in a PPPoE session is announced Ipv4, like a bare one. The common accessors (link_type(), network_protocol(), network_payload()) never assume Ethernet; the format-specific views are explicit (kind() to match on, or as_ethernet(), as_raw_ip(), as_linux_sll(), as_linux_sll2() and as_ieee80211(), which each return an Option):
#![allow(unused)] fn main() { println!("LINKTYPE={}", flow.data_link.link_type()); println!("next={:?}", flow.data_link.network_protocol()); if let Some(ethernet) = flow.data_link.as_ethernet() { println!("{} -> {}", ethernet.source_mac, ethernet.destination_mac); } if let Some(sll) = flow.data_link.as_linux_sll() { println!("{} type={}", sll.hardware_type, sll.packet_type); } }
A RAW or SLL capture therefore cannot come out with MAC addresses it never had, which is what happened when every format went through DataLink.
The formats
Each format has its page:
- Ethernet (LINKTYPE 1), with its MAC addresses, EtherType and VLAN tags;
- PPPoE session (EtherType
0x8864), peeled inside an Ethernet frame like a VLAN tag since 11.6.0; - Linux cooked capture, SLL (113) and SLL2 (276);
- RAW IP (101, 228, 229);
- BSD loopback (NULL, 0);
- IEEE 802.3br (274);
- and STP, which lives in Ethernet frames but has no network layer.
IEEE 802.11 is modelled (Ieee80211Link) for the inner flows of a CAPWAP tunnel, not yet decodable as a top-level LINKTYPE.
One error path
Whatever the format, a link failure is reported through the same enum, LinkLayerError (#[non_exhaustive]), with sizes that count the whole packet:
#![allow(unused)] fn main() { Err(ParseError::InvalidLinkLayer(LinkLayerError::Truncated { link_type, required, actual, })) }
Truncated is the only variant Ethernet produces: its decoder maps DataLinkError::DataLinkTooShort onto it, required counting the VLAN tags already met. The 802.3br decoder adds its preamble, SMD and mCRC to both sizes and the NULL decoder its four header bytes, so a consumer accounting for link failures never needs to know where a decoder slices the packet. The other variants name what is wrong instead of a size: InvalidIpVersion, InvalidAddressFamily, InvalidPreamble, InvalidSmd and PreemptibleFragment. An unsupported LINKTYPE is not among them: it is ParseError::UnsupportedLinkType. Neither is a malformed PPPoE session: the frame is kept unpeeled, with EtherType 0x8864 and no layer 3, never refused (PPPoE session).
Ethernet
LINKTYPE 1, the format of most captures. The data link page explains how the LINKTYPE selects this decoder.
The frame
| Bytes | Field | Meaning |
|---|---|---|
| 0–5 | Destination MAC address | the receiving interface, or a group of interfaces (multicast, broadcast) |
| 6–11 | Source MAC address | the sending interface |
| 12–13 | EtherType | the protocol of the payload, or a tag that precedes it |
| 14– | Payload | the packet of the next layer (IPv4, ARP...) |
MAC addresses
A MAC address is six bytes. The first three are the Organizationally Unique Identifier (OUI) of the manufacturer:
#![allow(unused)] fn main() { pub struct MacAddress(pub [u8; 6]); impl MacAddress { pub const fn is_broadcast(&self) -> bool; /// The I/G bit of the first byte: broadcast is multicast too. pub const fn is_multicast(&self) -> bool; pub const fn is_unicast(&self) -> bool; /// "ASUSTek:3c:4d:5e" when the OUI is known (the manufacturer replaces /// the first three bytes), "00:1a:2b:3c:4d:5e" otherwise. pub fn display_with_oui(&self) -> String; pub fn get_oui(&self) -> Oui; } }
The OUI table is embedded in the crate: no file to load, no network lookup. It is also short: a match on seven prefixes (ASUSTek, Intel, Sagemcom, three Siemens prefixes and PnMc, the PROFINET multicast prefix 01:0e:cf), not the IEEE registry. Any other prefix is Oui::Unknown, and display_with_oui() falls back to the plain address.
The EtherType
The EtherType is a two-byte big-endian value that names the protocol of the payload. Ethertype(pub u16) is a plain newtype: an unknown value is preserved, not refused, and static_name() returns None for it. The values the crate names include:
| EtherType (Hex) | Protocol |
|---|---|
0x0800 | IPv4 |
0x86DD | IPv6 |
0x0806 | ARP |
0x8892 | Profinet |
0x88F7 | PTP |
0x88B8 | GOOSE |
0x88CC | LLDP |
0x8100 | VLAN tag (802.1Q) |
0x88A8 / 0x9100 | Service tag (802.1ad / legacy QinQ) |
0x8864 | PPPoE session |
Naming is not decoding. Only the seven values that NetworkProtocol maps reach a decoder of the internet layer: IPv4, IPv6, ARP and Profinet, PTP (0x88F7) since 11.5.0, GOOSE (0x88B8) and LLDP (0x88CC) since 11.6.0. MRP (0x88E3), the PPPoE discovery stage (0x8863) and the rest of the name table only get a readable name, and internet stays None. The TPIDs never survive as the parsed ethertype: the parser consumes the tags they announce, and, since 11.6.0, a PPPoE session that carries IP (below).
VLAN tags
When the EtherType is a TPID (0x8100, 0x88A8 or 0x9100), the next 4 bytes are a VLAN tag (TCI + the following EtherType), and that EtherType may itself be a TPID: 802.1ad puts an S-tag in front of the C-tag, and some equipment stacks two 0x8100. The parser consumes the whole stack, so that ethertype and payload always describe the real layer 3:
#![allow(unused)] fn main() { #[non_exhaustive] pub struct DataLink<'a> { pub destination_mac: MacAddress, pub source_mac: MacAddress, /// The innermost tag (the customer VLAN), if any. pub vlan: Option<VlanTag>, /// The whole stack, outermost first (S-tag then C-tag). pub vlan_stack: VlanStack<'a>, /// The PPPoE session the frame belongs to, if any (11.6.0). pub pppoe: Option<PppoeSession>, /// The real layer-3 EtherType, after the tags and, when PPP carries IP, /// the PPPoE session. pub ethertype: Ethertype, pub payload: &'a [u8], } pub struct VlanTag { pub id: u16, // VLAN identifier (12 bits) pub pcp: u8, // priority code point (3 bits) pub dei: bool, // drop eligible indicator pub inner_ethertype: Ethertype, } }
vlan_stack.outer() gives the S-VLAN, vlan_stack.inner() the same tag as vlan, and vlan_stack.iter() walks the stack from outer to inner. VlanStack is a zero-copy view over the tag bytes of the frame: no allocation, whatever the depth (#82). It takes part in equality and hashing, so two frames that differ only by their S-tag are two flows, and it is serialized only when at least two tags are stacked, so the JSON of untagged and single-tagged frames did not change when it appeared in 11.0.0.
The Display of a VlanTag prints its ID and PCP in decimal since 11.5.0 (#134): ID: 100, PCP: 0, DEI: false, where VLAN 100 used to print as ID: 64, hexadecimal without a prefix. The Display of DataLink carries the same text.
The untagged case is the hot path and stays a straight line; the stack is unrolled in a separate #[inline(never)] function, because unrolling it inline cost about 13 ns on every frame, tagged or not (measured on the reference packet).
PPPoE sessions
When the EtherType, after the tags if there are any, is 0x8864, the frame belongs to a PPPoE session (RFC 2516), the link of a fibre or xDSL subscriber to the provider. Since 11.6.0 the session is peeled like a tag when PPP carries IPv4 (0x0021) or IPv6 (0x0057) (#172): ethertype and payload then describe that packet, bounded by the PPPoE length, and pppoe keeps the session, a PppoeSession with its identifier, its length and the PPP protocol. With a PPP control protocol (LCP, IPCP...), ethertype stays 0x8864 and payload is the PPP packet. The session identifier and the PPP protocol take part in equality and hashing, the PPPoE length does not, and the session is not serialized yet. The PPPoE session page has the details and the oracle.
Validations
| Bytes | Field | Check | Error |
|---|---|---|---|
| 0–13 | Two MAC addresses and the EtherType | the frame holds at least 14 bytes | DataLinkError::DataLinkTooShort { required, actual } |
| 14– | VLAN stack | checked again at each tag consumed: 14 + 4 × tags bytes | DataLinkTooShort |
| 0–5, 6–11 | MAC address | exactly 6 bytes | MacParseError::InvalidLength |
A frame cut in the middle of the VLAN stack is reported as too short, never read out of bounds. The MAC check cannot fail from DataLink::try_from, where the frame length is already proven; it protects a direct MacAddress::try_from.
These are the errors of DataLink::try_from called directly. Through parse, the Ethernet decoder converts them into LinkLayerError::Truncated (see One error path): since 11.0.0, DataLinkError is no longer part of ParseError.
The EtherType is not validated: an unknown value is a valid frame carrying a protocol the crate does not decode, and the internet layer will simply be None. A PPPoE session header that is not well formed is no error either: the frame keeps EtherType 0x8864, pppoe is None, and there is no layer 3.
#![allow(unused)] fn main() { /// Ethernet II header: two MACs and an EtherType. const DATALINK_HEADER_LEN: usize = 14; impl<'a> TryFrom<&'a [u8]> for DataLink<'a> { type Error = DataLinkError; fn try_from(packets: &'a [u8]) -> Result<Self, Self::Error> { validate_data_link_length(packets)?; let destination_mac = MacAddress::try_from(&packets[0..6])?; let source_mac = MacAddress::try_from(&packets[6..12])?; let raw_ethertype = u16::from_be_bytes([packets[12], packets[13]]); if VlanTag::is_tpid(raw_ethertype) { return Self::parse_tagged(packets, destination_mac, source_mac, raw_ethertype); } if raw_ethertype == PPPOE_SESSION_ETHERTYPE { return Ok(Self::parse_pppoe( destination_mac, source_mac, None, VlanStack::default(), &packets[DATALINK_HEADER_LEN..], )); } Ok(DataLink { destination_mac, source_mac, vlan: None, vlan_stack: VlanStack::default(), pppoe: None, ethertype: Ethertype::from(raw_ethertype), payload: &packets[DATALINK_HEADER_LEN..], }) } } }
Called directly, DataLink::try_from assumes Ethernet: it checks lengths, never that the bytes are Ethernet, so a Linux SLL frame comes back Ok with fabricated MAC addresses. It is kept for compatibility and announced for removal in a future major release. Inside the crate it is only called where something declares Ethernet: the LINKTYPE (Ethernet, 802.3br express mPackets) or a tunnel header (VXLAN, and GRE or Geneve announcing 0x6558).
The parsed frame
PPPoE session
PPP over Ethernet, RFC 2516: the link that a fibre or xDSL subscriber's router keeps with the provider's access concentrator, and that carries all of the subscriber's IP traffic. Up to 11.5.0 its session stage, EtherType 0x8864, was only named, and the IP packets inside had no internet layer; since 11.6.0 the session is peeled (#172, #173). The module is packet_parser::parse::data_link::pppoe. The session is not a layer of PacketFlow: like a VLAN tag, it is consumed by the Ethernet decoder and kept in the Ethernet view, DataLink::pppoe.
Peeled like a VLAN tag
There is no port, no probe and no Decode As: the EtherType announces the session, and the Ethernet decoder takes its word, as it does for a TPID. DataLink::try_from reads the EtherType after the two MAC addresses; a TPID sends the frame through the VLAN stack first, and parse_tagged makes the same test on the EtherType that follows the last tag. A session is therefore peeled under any number of tags, or none:
#![allow(unused)] fn main() { // DataLink::try_from, after the two MAC addresses. let raw_ethertype = u16::from_be_bytes([packets[12], packets[13]]); if VlanTag::is_tpid(raw_ethertype) { return Self::parse_tagged(packets, destination_mac, source_mac, raw_ethertype); } if raw_ethertype == PPPOE_SESSION_ETHERTYPE { return Ok(Self::parse_pppoe( destination_mac, source_mac, None, VlanStack::default(), &packets[DATALINK_HEADER_LEN..], )); } }
parse_pppoe then decides what ethertype and payload become:
#![allow(unused)] fn main() { #[inline(never)] fn parse_pppoe( destination_mac: MacAddress, source_mac: MacAddress, vlan: Option<VlanTag>, vlan_stack: VlanStack<'a>, payload: &'a [u8], ) -> Self { let (pppoe, ethertype, payload) = match peel_session(payload) { Some((session, inner)) => ( Some(session), session.inner_ethertype().unwrap_or(PPPOE_SESSION_ETHERTYPE), inner, ), None => (None, PPPOE_SESSION_ETHERTYPE, payload), }; DataLink { destination_mac, source_mac, vlan, vlan_stack, pppoe, ethertype: Ethertype::from(ethertype), payload, } } }
Three outcomes, then:
After EtherType 0x8864 | pppoe | ethertype | payload | Internet layer |
|---|---|---|---|---|
a session carrying PPP IPv4 (0x0021) or IPv6 (0x0057) | Some(session) | 0x0800 or 0x86DD | the IP packet | IPv4 or IPv6, then transport and application as usual |
| a session carrying any other PPP protocol (LCP, IPCP, IPv6CP, PAP, CHAP...) | Some(session) | 0x8864 | the PPP packet, after its protocol field | None, nothing in corrupted |
| no well-formed session data frame | None | 0x8864 | all the bytes after the EtherType | None, nothing in corrupted |
inner_ethertype (crate-internal) maps 0x0021 to 0x0800 and 0x0057 to 0x86DD, and nothing else. From there on, the layers above see what they would see without PPPoE: network_protocol() is Ipv4 or Ipv6, network_payload() is the packet, and the internet layer dispatches on it as on any other. Tags, when there are any, are kept as they were read: vlan.inner_ethertype still says 0x8864, the value that follows the tag on the wire. Like the tag stack, the session is unwrapped in a separate #[inline(never)] function, off the straight line of an untagged frame.
Since the peeling lives in DataLink::try_from, it happens wherever the crate reads an Ethernet frame: LINKTYPE 1, an 802.3br express mPacket, and the inner frame of a VXLAN tunnel or of a GRE or Geneve one announcing 0x6558 (tunnels).
An IPv4 session under two VLAN tags, then an IPv6 one under a single tag that reaches the application layer (tested):
#![allow(unused)] fn main() { #[test] fn a_pppoe_session_carrying_ipv4_is_peeled_like_a_vlan_tag() { // Frame 1 of pppoe-over-qinq.pcap: two VLAN tags, EtherType 0x8864, // a PPPoE session carrying PPP IPv4, then a TCP SYN. let raw = hex::decode(QINQ_PPPOE_IPV4_SYN_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let ethernet = flow.data_link.as_ethernet().unwrap(); // The tags are consumed first, then the session... let tags: Vec<u16> = ethernet.vlan_stack.iter().map(|tag| tag.id).collect(); assert_eq!(tags, [3704, 2474]); // (the inner tag keeps the EtherType that followed it on the wire) let inner_tag = ethernet.vlan.as_ref().unwrap(); assert_eq!(inner_tag.inner_ethertype.0, PPPOE_SESSION_ETHERTYPE); let session = ethernet.pppoe.expect("a PPPoE session"); assert_eq!(session.session_id, 0x0f07); assert_eq!(session.length, 66); // the PPP protocol field and the packet assert_eq!(session.ppp_protocol, 0x0021); assert_eq!(session.ppp_protocol_name(), Some("IPv4")); // ...so that `ethertype` and `payload` describe the packet PPP carries: // the 64 bytes after 14 + 2 x 4 + 6 + 2. assert_eq!(ethernet.ethertype.0, 0x0800); assert_eq!(flow.data_link.network_protocol(), NetworkProtocol::Ipv4); assert_eq!(ethernet.payload, &raw[30..]); assert_eq!(ethernet.payload.len(), 64); // From there on, the pipeline is the usual one. let internet = flow.internet.as_ref().expect("IPv4"); assert_eq!(internet.source.unwrap().to_string(), "1.1.1.1"); assert_eq!(internet.destination.unwrap().to_string(), "2.2.2.2"); let transport = flow.transport.as_ref().expect("TCP"); assert_eq!(transport.source_port, Some(20394)); assert_eq!(transport.destination_port, Some(443)); assert!(flow.corrupted.is_none()); } }
#![allow(unused)] fn main() { #[test] fn a_pppoe_session_carrying_ipv6_reaches_the_application_layer() { // Frame 10 415 of The-Ultimate-PCAP.pcapng: a subscriber's router asks // for an IPv6 prefix over its PPPoE session, under VLAN 7. let raw = hex::decode(PPPOE_IPV6_DHCPV6_SOLICIT_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let ethernet = flow.data_link.as_ethernet().unwrap(); assert_eq!(ethernet.vlan.as_ref().map(|tag| tag.id), Some(7)); let session = ethernet.pppoe.unwrap(); assert_eq!((session.session_id, session.length), (0x8f9e, 149)); assert_eq!(session.ppp_protocol_name(), Some("IPv6")); assert_eq!(flow.data_link.network_protocol(), NetworkProtocol::Ipv6); // The PPPoE length bounds the packet: the four bytes after it, at the // end of the 177-byte frame, are not handed to IPv6. assert_eq!(raw.len(), 14 + 4 + 6 + 149 + 4); assert_eq!(ethernet.payload, &raw[26..raw.len() - 4]); let internet = flow.internet.as_ref().expect("IPv6"); assert_eq!(internet.protocol_name, "IPv6"); assert_eq!(internet.source_type, Some(IpType::LinkLocal)); assert_eq!(internet.destination.unwrap().to_string(), "ff02::1:2"); let transport = flow.transport.as_ref().expect("UDP"); assert_eq!(transport.source_port, Some(546)); assert_eq!(transport.destination_port, Some(547)); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "DHCPv6"); } }
The session: PppoeSession
Doc comments shortened:
#![allow(unused)] fn main() { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)] #[non_exhaustive] pub struct PppoeSession { /// The session identifier, chosen by the access concentrator. pub session_id: u16, /// Declared length of the PPPoE payload, PPP protocol field included. pub length: u16, /// PPP protocol (RFC 1661 §2). A field compressed on one byte (PFC, /// RFC 1661 §6.5) is widened to sixteen bits: 0x21 is 0x0021. pub ppp_protocol: u16, } impl PppoeSession { /// The name of the PPP protocol, when it is known. pub fn ppp_protocol_name(&self) -> Option<&'static str>; } }
The six bytes of the PPPoE header, then the PPP protocol field; offsets from the first byte after the EtherType 0x8864, which is byte 14 of an untagged frame, 18 under one tag, 22 under two:
| Bytes | Field | Note |
|---|---|---|
| 0 | version (high nibble), type (low nibble) | both 1: 0x11 |
| 1 | code | 0x00, session data |
| 2–3 | session_id | |
| 4–5 | length | the PPPoE payload: the protocol field and the PPP packet |
| 6–7 | ppp_protocol | byte 6 alone when the field is compressed |
| 8… | the PPP packet | payload, from byte 7 when the field is compressed |
PppoeSession is #[non_exhaustive]: it is read from a parsed frame, never built outside the crate. PPPOE_SESSION_ETHERTYPE, the public constant 0x8864, lives in the same module. ppp_protocol_name() knows nine protocols, and only the first two are peeled:
ppp_protocol | ppp_protocol_name() | ethertype after peeling |
|---|---|---|
0x0021 | "IPv4" | 0x0800 |
0x0057 | "IPv6" | 0x86DD |
0xC021 | "LCP" | 0x8864 |
0xC023 | "PAP" | 0x8864 |
0xC223 | "CHAP" | 0x8864 |
0x8021 | "IPCP" | 0x8864 |
0x8057 | "IPv6CP" | 0x8864 |
0xC025 | "LQR" | 0x8864 |
0x80FD | "CCP" | 0x8864 |
| any other | None | 0x8864 |
The Display of DataLink gives the session a line of its own, PPPoE: session 0x8f9e, PPP LCP, the protocol in hexadecimal when it has no name.
What makes a session
peel_session, crate-internal, is the whole check:
#![allow(unused)] fn main() { pub(crate) fn peel_session(payload: &[u8]) -> Option<(PppoeSession, &[u8])> { let header = payload.get(..PPPOE_HEADER_LEN)?; if header[0] != PPPOE_VERSION_TYPE || header[1] != PPPOE_SESSION_DATA { return None; } // The low byte of a PPP protocol is odd, its high byte even (RFC 1661 // §2): an odd first byte is a compressed field (PFC), which RFC 2516 §7 // discourages without forbidding it. let (ppp_protocol, protocol_len) = match *payload.get(PPPOE_HEADER_LEN..)? { [low, ..] if low & 1 == 1 => (u16::from(low), PPP_COMPRESSED_PROTOCOL_LEN), [high, low, ..] => (u16::from_be_bytes([high, low]), PPP_PROTOCOL_LEN), _ => return None, }; let length = u16::from_be_bytes([header[4], header[5]]); let declared = usize::from(length); if declared < protocol_len { return None; } let end = payload.len().min(PPPOE_HEADER_LEN + declared); Some(( PppoeSession { session_id: u16::from_be_bytes([header[2], header[3]]), length, ppp_protocol, }, &payload[PPPOE_HEADER_LEN + protocol_len..end], )) } }
A session data frame (RFC 2516 §6) has the six header bytes, version and type 0x11, code 0x00, a PPP protocol field, and a length that covers at least that field. When one of them is missing, nothing is an error: the frame is left as it is, pppoe None, EtherType 0x8864 and the whole payload, like an unknown EtherType. No internet layer, nothing in corrupted, and the parse never fails because of it; there is no PPPoE error type.
The protocol field may be compressed to one byte (PFC). A PPP protocol has an even high byte and an odd low byte, so an odd first byte can only be the low byte of a one-byte field, which is how tshark reads it too: 0x21 is IPv4 and is reported as 0x0021. No frame of the corpus uses it (all 6 881 session frames of the two captures below carry a two-byte field); the unit tests of pppoe.rs cover it on built bytes.
Bounded like tshark does
Counted from the PPPoE header, the PPP packet ends at byte 6 + length or at the end of the frame, whichever comes first:
- the PPPoE length first: what the frame holds after it is not PPP, and the padding of a short Ethernet frame is left out of
payload; - then the end of the frame: a length beyond the captured bytes, a truncated capture, is bounded by them;
- a PPPoE length shorter than the IP packet truncates it, as tshark does, and the Linux kernel's
pppoe_rcv, which trims the frame to that length. The internet layer then finds a total length beyond its buffer, and the frame is reported corrupted.
The last case is real: six ACKs of pcaps_exemple/vlan/pppoe-over-qinq.pcap (frames 19, 33, 41, 47, 63 and 81) carry a PPPoE length of 42 for a 46-byte IPv4 packet, and tshark flags them as well (Possible bad payload length 42 != 48, IPv4 total length exceeds packet length (40 bytes)). The session is kept; the IPv4 layer is the one reported (tested):
#![allow(unused)] fn main() { #[test] fn a_pppoe_length_shorter_than_the_ip_packet_truncates_it() { // Frame 19 of pppoe-over-qinq.pcap: a PPPoE length of 42, and 46 bytes // in the frame after the PPP protocol field. let raw = hex::decode(QINQ_PPPOE_SHORT_LENGTH_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let ethernet = flow.data_link.as_ethernet().unwrap(); assert_eq!(ethernet.pppoe.unwrap().length, 42); assert_eq!(raw.len() - 30, 46); assert_eq!(ethernet.payload.len(), 40); // 42 minus the protocol field // The IPv4 header announces 46 bytes, the PPPoE length gave it 40: // the session is kept, the internet layer is reported corrupted. assert!(flow.internet.is_none()); let corrupted = flow.corrupted.expect("a corrupted internet layer"); assert_eq!(corrupted.layer, CorruptedLayerKind::Internet); assert_eq!( corrupted.error.to_string(), "IPv4 error: Invalid total length: expected 46 bytes (header: 20 + data: 26), \ but got 40 bytes" ); } }
Control protocols keep 0x8864
LCP, the authentication protocols (PAP, CHAP) and the network control protocols (IPCP, IPv6CP) set up the link and carry no IP packet. The session is kept in pppoe, but ethertype stays 0x8864, network_protocol() is NetworkProtocol::Other(0x8864), and payload is the PPP packet after its protocol field, raw. The internet layer is None with nothing in corrupted, which is how every PPPoE frame came out up to 11.5.0. An LCP Configure-Request of the Ultimate PCAP, whose 64-byte frame holds 24 bytes beyond the PPPoE length (tested):
#![allow(unused)] fn main() { #[test] fn a_ppp_control_protocol_keeps_ethertype_0x8864() { // Frame 10 401 of The-Ultimate-PCAP.pcapng: an LCP Configure-Request // on session 0x8f9e, in a 64-byte frame. let raw = hex::decode(PPPOE_LCP_CONFIGURE_REQUEST_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let ethernet = flow.data_link.as_ethernet().unwrap(); let session = ethernet.pppoe.unwrap(); assert_eq!(session.ppp_protocol, 0xc021); assert_eq!(session.ppp_protocol_name(), Some("LCP")); // No IP packet to reach: the EtherType stays the session's... assert_eq!(ethernet.ethertype.0, PPPOE_SESSION_ETHERTYPE); assert_eq!(ethernet.ethertype.static_name(), Some("Pppoe Session Stage")); assert_eq!(flow.data_link.network_protocol(), NetworkProtocol::Other(0x8864)); // ...and the payload is the PPP packet, after the protocol field and // within the PPPoE length (16): Configure-Request, identifier 1, // length 14. The 24 bytes that follow are left out. assert_eq!(ðernet.payload[..4], [0x01, 0x01, 0x00, 0x0e]); assert_eq!(ethernet.payload.len(), 14); assert_eq!(raw.len(), 14 + 4 + 6 + 16 + 24); // Not decoded is not corrupt: no internet layer, nothing reported. assert!(flow.internet.is_none()); assert!(flow.corrupted.is_none()); assert!(ethernet.to_string().ends_with("PPPoE: session 0x8f9e, PPP LCP\n")); } }
Flow identity
DataLink compares and hashes the session through one key, the session identifier and the PPP protocol:
#![allow(unused)] fn main() { /// What identifies a flow in a PPPoE session: the session and the PPP /// protocol. The PPPoE length changes with every packet, like the payload, /// and is not part of it. fn pppoe_flow_key(&self) -> Option<(u16, u16)> { self.pppoe .map(|session| (session.session_id, session.ppp_protocol)) } }
Two packets that differ only by their PPPoE length and their payload are one flow, and two sessions are two flows. Since a control protocol leaves the EtherType at 0x8864, the PPP protocol is what separates the LCP of a session from its IPCP. PppoeSession itself derives PartialEq, length included: the key is a property of DataLink, not of the session value.
The owned model has no session at all (next section), so it makes neither distinction: as PacketFlowOwned, the LCP and the IPCP of a session are the same flow, and so are two sessions that agree on everything else (tested for the first):
#![allow(unused)] fn main() { #[test] fn the_pppoe_length_is_not_part_of_the_flow_identity() { fn hash_of(flow: &PacketFlow<'_>) -> u64 { let mut hasher = DefaultHasher::new(); flow.hash(&mut hasher); hasher.finish() } fn session_id_and_length(flow: &PacketFlow<'_>) -> (u16, u16) { let session = flow.data_link.as_ethernet().unwrap().pppoe.unwrap(); (session.session_id, session.length) } // Frames 1 and 3 of pppoe-over-qinq.pcap: the SYN and an ACK of the // same connection, in the same session, in PPPoE lengths 66 and 42. let raw_syn = hex::decode(QINQ_PPPOE_IPV4_SYN_HEX).unwrap(); let raw_ack = hex::decode(QINQ_PPPOE_IPV4_ACK_HEX).unwrap(); let syn = parse(LinkType::ETHERNET, &raw_syn).unwrap(); let ack = parse(LinkType::ETHERNET, &raw_ack).unwrap(); assert_eq!(session_id_and_length(&syn), (0x0f07, 66)); assert_eq!(session_id_and_length(&ack), (0x0f07, 42)); assert_eq!(syn, ack); // one flow assert_eq!(hash_of(&syn), hash_of(&ack)); // Frames 10 401 and 10 409 of The-Ultimate-PCAP.pcapng: LCP and IPCP // of one session, both under EtherType 0x8864. The PPP protocol is // what tells them apart... let raw_lcp = hex::decode(PPPOE_LCP_CONFIGURE_REQUEST_HEX).unwrap(); let raw_ipcp = hex::decode(PPPOE_IPCP_CONFIGURE_ACK_HEX).unwrap(); let lcp = parse(LinkType::ETHERNET, &raw_lcp).unwrap(); let ipcp = parse(LinkType::ETHERNET, &raw_ipcp).unwrap(); assert_eq!(session_id_and_length(&lcp).0, session_id_and_length(&ipcp).0); assert_ne!(lcp, ipcp); // two flows // ...and the owned model, which has no session, cannot. assert_eq!(lcp.to_owned_flow(), ipcp.to_owned_flow()); } }
JSON: not yet
pppoe is #[serde(skip_serializing)]. Adding the field to DataLink was not a break, the struct being #[non_exhaustive]; DataLinkOwned is an exhaustive struct and cannot gain it without one, and both models must serialize to the same JSON. So the session is not serialized yet, but what it carries is: ethertype names the packet, "IPv4" where 11.5.0 wrote "Pppoe Session Stage", and the internet, transport and application layers are there as for any frame (tested):
#![allow(unused)] fn main() { #[test] fn the_session_is_not_serialized_yet() { let raw = hex::decode(QINQ_PPPOE_IPV4_SYN_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let json = serde_json::to_value(&flow).unwrap(); // The JSON describes the packet PPP carries... assert_eq!(json["data_link"]["link_details"]["ethertype"], "IPv4"); assert_eq!(json["protocol_internet"], "IPv4"); assert_eq!(json["destination_port"], 443); // ...and holds no trace of the session. assert!(!serde_json::to_string(&flow).unwrap().contains("pppoe")); // The owned model, which cannot carry it, gives the same JSON. assert_eq!(serde_json::to_value(flow.to_owned_flow()).unwrap(), json); // A SYN has no application layer. The DHCPv6 Solicit of frame 10 415 // of The-Ultimate-PCAP.pcapng has one, serialized like any other. let raw = hex::decode(PPPOE_IPV6_DHCPV6_SOLICIT_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let json = serde_json::to_value(&flow).unwrap(); assert_eq!(json["data_link"]["link_details"]["ethertype"], "IPv6"); assert_eq!(json["application_protocol"], "DHCPv6"); assert_eq!(serde_json::to_value(flow.to_owned_flow()).unwrap(), json); } }
Oracle: 6 795 session frames
The golden test tests/pppoe_golden.rs reads pcaps_exemple/The-Ultimate-PCAP.pcapng in place and compares every frame that tshark 4.6.6 decodes as pppoes with the oracle frozen in tests/data/pppoe_tshark_oracle.tsv (tools/pppoe_oracle.sh): session identifier, PPPoE length, PPP protocol, the protocol after the first IP header, and the UDP or TCP ports. The crate peels a session on exactly those 6 795 frames and on no other frame of the capture, all of them without a corruption. The Ultimate PCAP merges many captures, and these frames belong to five sessions between four pairs of MAC addresses, all under VLAN 7. 0x001e carries the 6 486 IPv4 frames, 0x8f9e 34 control messages and 194 DHCPv6 messages, 0xe579 the 78 IPv4 packets in IPv6, 0x1f3d two more DHCPv6 messages, and 0x8f80, between the same two MAC addresses as 0x8f9e, a single LCP message before the PADT that ends it. By PPP protocol:
| PPP protocol | Frames | What PPP carries, as tshark reads it |
|---|---|---|
IPv4 0x0021 | 6 486 | 6 483 UDP datagrams (RTP and SIP), 2 ICMP messages, 1 non-initial fragment |
IPv6 0x0057 | 274 | 196 DHCPv6 messages over UDP, 78 IPv4 packets in IPv6 (TCP) |
LCP 0xC021 | 26 | control |
IPCP 0x8021 | 5 | control |
IPv6CP 0x8057 | 4 | control |
One difference is named: frame 15 114, the first of two fragments of a 2 017-byte SIP datagram, whose UDP header tshark reads while the crate decodes no transport in a fragment (IPv4 fragments).
On the 11.5.0 corpus, the IP frames of these sessions gained their internet and transport layers: 6 482 went from no application to "Unknown", 196 to "DHCPv6" and 78 to the "IP-in-IP" tunnel label.
The second capture, pcaps_exemple/vlan/pppoe-over-qinq.pcap, is the one of tests/qinq_golden.rs: 86 frames under two 802.1Q tags (VID 3704 then 2474), session 0x0f07, PPP IPv4 throughout. Since 11.6.0 the test follows them past the session down to TCP, except the six frames of the short PPPoE length. No fuzz target is dedicated to the session: parse_packetflow and parse_linktype hand arbitrary bytes to the Ethernet decoder, the peeling included.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- The discovery stage, EtherType
0x8863(PADI, PADO, PADR, PADS, PADT), is only named ("Pppoe Discovery Stage"):pppoestaysNoneand there is no internet layer. The Ultimate PCAP has eight of them, among which the PADT that ends session0x8f80(frame 10 396) and the PADS that assigns session0x8f9e(frame 10 400), just before the first LCP message of that session. - PPP control protocols are named, not decoded: LCP options, the PAP or CHAP exchange and the IPCP addresses stay in the raw
payload. - No session state: the crate does not follow a discovery to its session, nor tie a session identifier to its MAC addresses. One frame at a time, like the rest of the crate.
- The JSON and the owned model do not carry the session yet (see above).
- Only the Ethernet view peels it: a Linux cooked capture whose protocol field is
0x8864keepsNetworkProtocol::Other(0x8864), and a capture declared as LINKTYPE 51 (PPP_ETHER), whose packets start at the PPPoE header, is refused like any LINKTYPE without a decoder (ParseError::UnsupportedLinkType).
Linux cooked capture (SLL)
The Linux cooked formats are what a capture on the Linux any interface produces: a pseudo-header instead of an Ethernet one.
SLL v1
A 16-byte cooked header, in network byte order. The decoder keeps the packet type, the raw ARPHRD hardware type, the declared address length, the available source-address bytes and the protocol value. Packet types and hardware types outside the known constants are preserved as numbers, so a newer kernel does not turn packets into errors. An address longer than the 8-byte wire slot is reported as truncated (address_is_truncated()) rather than rejected. Use LinkType::LINUX_SLL (113): the value 25 shown by some Wireshark fields is an internal WTAP identifier.
SLL v2
A 20-byte header. The decoder additionally keeps the interface index, numeric because resolving its name belongs to the capture machine, and the reserved-MBZ field. A non-zero reserved value is preserved and reported by reserved_is_zero(), matching Tshark's tolerant dissection. Use LinkType::LINUX_SLL2 (276); Wireshark's internal WTAP identifier for this format is 210.
RAW IP
LINKTYPE RAW (101), IPV4 (228) and IPV6 (229): the bytes start directly at the IP header. An empty packet is LinkLayerError::Truncated (one byte required), a version nibble other than 4/6 is LinkLayerError::InvalidIpVersion. With LinkType::IPV4/IPV6 the declared version is checked against the nibble, a mismatch being InvalidIpVersion too, and link_type() reports the LINKTYPE the capture declared instead of normalizing it to RAW. Once the version is known, an invalid IP header is an L3 corruption reported in corrupted, not a link error.
BSD loopback (NULL)
LINKTYPE 0, decoded since 11.2.0 (#95): four bytes of address family, then the IP packet. The family is written in the byte order of the capturing host and the format keeps no trace of it, so the field is read in both byte orders and the reading that names a known family is kept; that family must then agree with the IP version nibble: it is a cross-check, not the source of truth. AF_INET is 2 everywhere; AF_INET6 is accepted under every value Wireshark's epan/aftypes.h lists (10 Linux, 24 NetBSD/OpenBSD/BSD/OS, 26 Solaris, 28 FreeBSD/DragonFly, 30 Darwin), because a shorter list would reject the captures of a whole platform. 23 is deliberately refused: it is AF_INET6 on Windows but AF_IPX on BSD, which is how Wireshark's packet-null.c reads it, and overruling the reference dissector would take a capture that attests the Windows reading; the repository has none. An unknown or contradicting family is LinkLayerError::InvalidAddressFamily (its family is the little-endian reading). The decoded packet is a RawIp view whose link_type() stays NULL. LINKTYPE_LOOP (108), the OpenBSD twin in network order, is deliberately not handled: no capture attests it.
IEEE 802.3br
LINKTYPE 274 (#79). An mPacket wraps the frame in a preamble, an SMD and a trailing 4-byte mCRC. Express mPackets (SMD-E, 0xd5) are decoded as Ethernet once that wrapping is removed: as_ethernet() returns the frame while link_type() stays 274. The preamble is at most 7 octets of 0x55 and the standard lets the PHY shorten it, so the SMD is located as the first non-0x55 octet: the corpus contains 6-octet preambles, and a fixed offset left 102 real frames in error. Preemptible fragments (SMD-S/C) are refused with LinkLayerError::PreemptibleFragment, their reassembly being stateful; a first byte other than 0x55 is InvalidPreamble, an unknown SMD is InvalidSmd.
STP
Spanning Tree BPDUs are 802.3 frames (a length field instead of an EtherType) sent to 01:80:c2:00:00:00 with an LLC header 42-42-03. They have no network layer, and DataLink does not tell a length from an EtherType: a value up to 0x05DC lands in ethertype as an unknown value. Without a dedicated check they came out with L3/L4/L7 all None and no signal, so the pipeline validates the BPDU and labels the flow ApplicationProtocol::Stp ("STP") directly from the link layer (#4).
The check needs an Ethernet view (as_ethernet(), so an 802.3br express frame qualifies too), the bridge group address, a length field of at most 0x05DC that bounds LLC + BPDU (Ethernet padding beyond it is never parsed), the 42-42-03 header (which leaves out PVST+, carried in SNAP) and a BPDU that BpduPacket::try_from accepts. That decoder is public in parse::data_link::stp: it covers STP, RSTP and MSTP and fails with StpError. The flow itself only carries the label.
Internet
The internet layer is the first optional layer: it is parsed from LinkLayer::network_payload(), and the link layer says which protocol to expect through NetworkProtocol: Ipv4 (EtherType 0x0800), Ipv6 (0x86DD), Arp (0x0806), Profinet (0x8892), Ptp (0x88F7, since 11.5.0), Goose (0x88B8) and Lldp (0x88CC), both since 11.6.0, or Other(u16) for any other value. The enum is #[non_exhaustive], and its three late variants are declared after Other(u16), at its end. A RAW-IP capture announces Ipv4 or Ipv6 directly, without inventing an EtherType. Since 11.6.0, an IPv4 or IPv6 packet in a PPPoE session is announced Ipv4 or Ipv6 too, once the Ethernet decoder has peeled the session.
PTP on 0x88F7, GOOSE and LLDP travel straight over Ethernet, without IP: for them, the frame itself is the internet layer, decoded, without addresses, and nothing is parsed above it.
ICMP and ICMPv6 are not part of this layer: like TCP and UDP, they are selected by payload_protocol and decoded by the transport layer.
The Internet struct
Abridged (doc comments shortened):
#![allow(unused)] fn main() { #[derive(Debug, Clone, Serialize)] #[non_exhaustive] pub struct Internet<'a> { #[serde(rename = "source_ip")] pub source: Option<IpAddr>, #[serde(rename = "ip_source_type")] pub source_type: Option<IpType>, #[serde(rename = "destination_ip")] pub destination: Option<IpAddr>, #[serde(rename = "ip_destination_type")] pub destination_type: Option<IpType>, /// "IPv4", "IPv6", "ARP", "Profinet", "PTP", "GOOSE" or "LLDP" #[serde(rename = "protocol_internet")] pub protocol_name: &'static str, /// Transport protocol parsable from `payload`. `None` when nothing above /// can be parsed: IP fragments, IPv6 No Next Header, ARP, Profinet, PTP, /// GOOSE, LLDP. #[serde(skip_serializing)] pub payload_protocol: Option<TransportProtocol>, #[serde(skip_serializing)] pub payload: &'a [u8], /// Full parsed header: Ipv4Packet, Ipv6Packet, ArpPacket, PtpPacket, /// GoosePacket or LldpPacket; None for Profinet. #[serde(skip_serializing)] pub details: Option<InternetDetails<'a>>, } }
The serde renames give the borrowed model and the owned one (InternetOwned) a single JSON schema (#22, 11.0.0): in the flattened flow object, source_ip next to source_port and source_mac is less ambiguous than source. payload_protocol, payload and details are not serialized, and PartialEq/Hash compare the first six fields only. InternetDetails (Ipv4, Ipv6, Arp, Ptp, and since 11.6.0 Goose and Lldp) is #[non_exhaustive] like Internet itself: a match on it needs a _ arm. It has no PROFINET variant: a PROFINET frame is validated, and its details is None.
Two helpers answer the usual questions about the destination (issue #9): destination_is_multicast() reads destination_type, and destination_is_limited_broadcast() reads the address itself and tests it for 255.255.255.255.
Address classification: IpType
Addresses use the standard std::net::IpAddr, and each one is classified by IpType::from_addr. An IPv4-mapped IPv6 address, ::ffff:a.b.c.d, takes the class of the IPv4 it carries (RFC 4291 §2.5.5.2): a dual-stack socket logs its IPv4 clients in that form, and ::ffff:192.168.1.1 is Private. For every other address, the first matching row wins:
IpType | IPv4 | IPv6 |
|---|---|---|
Broadcast | 255.255.255.255 only (limited broadcast) | — |
Private | RFC 1918: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 | — |
Loopback | 127.0.0.0/8 | ::1 |
Apipa | 169.254.0.0/16 | — |
Multicast | 224.0.0.0/4 | ff00::/8 |
Documentation | 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24 | 2001:db8::/32, 3fff::/20 |
LinkLocal | never: 169.254.0.0/16 is already Apipa | fe80::/10 |
Ula | — | fc00::/7 |
Unknown | 0.0.0.0 | :: |
Public | anything else | anything else |
Public is the fallback, not a proof of global reachability: the shared address space 100.64.0.0/10 (carrier-grade NAT), the benchmarking range 198.18.0.0/15, and the reserved 240.0.0.0/4, 255.255.255.255 aside, all come out Public.
IpType is a property of the address alone. It says which range an address belongs to, never where the host sits relative to the capture point: a Private peer can be across a VPN or a routed WAN, a Public one can be on the same LAN, and the directed broadcast 192.168.1.255 comes out Private, because recognizing it needs the subnet mask, which a packet parser does not have. What the enum saves a consumer is re-implementing the RFC 1918 and special-range tables; a filter such as "traffic leaving the site" still needs the site's own prefixes.
Broadcast was added in 11.0.0 (#9) and is declared last, after Unknown: inserted in second position, it would have shifted the discriminant of every following variant (IpType::Multicast as u8 from 1 to 2), a silent break for anyone storing those values. A test locks the historical discriminants, and the enum is #[non_exhaustive]. The JSON form of an IpType is the variant name ("Private", "Public"); its Display prints French labels (Privée, Publique, Inconnue).
Three IPv6 classifications changed in 11.5.0 (#136), all visible in the JSON as ip_source_type and ip_destination_type: link-local is the whole fe80::/10 (RFC 4291 §2.5.6), where fe81:: to febf:: came out Public; an IPv4-mapped address takes the class of the IPv4 it carries, where ::ffff:192.168.1.1 came out Public; and the documentation prefixes 2001:db8::/32 (RFC 3849) and 3fff::/20 (RFC 9637) are Documentation like their IPv4 counterparts, no longer Public. The discriminants did not move.
Dispatch on the announced protocol, not probing
The link layer has already said what the payload is. The internet parser trusts that announcement:
#![allow(unused)] fn main() { pub fn try_from_network_parts( protocol: NetworkProtocol, payload: &'a [u8], ) -> Result<Self, InternetError> { match protocol { NetworkProtocol::Arp => Ok(Self::from_arp(ArpPacket::try_from(payload)?)), NetworkProtocol::Ipv4 => Ok(Self::from_ipv4(ipv4::Ipv4Packet::try_from(payload)?)), NetworkProtocol::Ipv6 => Ok(Self::from_ipv6(ipv6::Ipv6Packet::try_from(payload)?)), NetworkProtocol::Profinet => { // Every RT frame is valid by its Frame ID; only a DCP Frame ID // must carry a readable DCP message (#133). profinet::validate_frame(payload)?; Ok(Self::profinet()) } NetworkProtocol::Ptp => match PtpPacket::try_from(payload) { Ok(ptp_packet) => Ok(Self::from_ptp(ptp_packet)), // A version or a message type the crate does not know is not a // corruption: the frame is not supported, as before 11.5.0. Err( PtpPacketParseError::UnsupportedVersion(_) | PtpPacketParseError::ReservedMessageType(_), ) => Err(InternetError::UnsupportedProtocol), Err(error) => Err(error.into()), }, NetworkProtocol::Goose => Ok(Self::from_goose(GoosePacket::try_from(payload)?)), NetworkProtocol::Lldp => Ok(Self::from_lldp(LldpPacket::try_from(payload)?)), NetworkProtocol::Other(_) => Err(InternetError::UnsupportedProtocol), } } }
Internet::try_from_parts(Ethertype, &[u8]) is the same call for a caller that holds an Ethernet Ethertype.
Why dispatch rather than "try ARP, then IPv4, then IPv6"? Because probing cannot tell a corrupt packet from an unknown protocol: both just fail every parser. With the EtherType in hand, the two cases are distinct, and the pipeline maps them to the two distinct outcomes (before 5.0.0, a corrupt packet under a known EtherType was silently swallowed):
#![allow(unused)] fn main() { match Internet::try_from_network_parts(network_protocol, network_payload) { Ok(internet) => (Some(internet), None), Err(InternetError::UnsupportedProtocol) => (None, None), // e.g. MRP, 0x88E3: not our job Err(e) => (None, Some(CorruptedLayer::from(e))), // said IPv4, was garbage } }
InternetError wraps one error type per protocol through #[from] (ArpError, Ipv4Error, Ipv6Error, ProfinetPacketError, since 11.5.0 PtpPacketParseError, and since 11.6.0 GooseParseError and LldpParseError, as GooseError and LldpError at the end of the enum), and CorruptedLayer::from deduces layer from it. Since 13.0.0 CorruptedLayer::error carries that error, as CorruptedLayerError::Internet, and a match sorts the causes; its Display is the text of 12.x, for instance IPv4 error: Invalid total length: expected 40 bytes (header: 20 + data: 20), but got 20 bytes, or GOOSE error: … and LLDP error: … for the two new ones. Some declared variants are never returned by the parsers: Ipv4Error::InvalidChecksum, TtlExpired, UnsupportedProtocol, InvalidOption, FragmentedPacket and PacketTooLarge; Ipv6Error::HopLimitExpired, UnsupportedNextHeader, PacketTooLarge and InvalidAddress; InternetError::InvalidLength, InvalidFormat and InvalidChecksum. A wrong checksum, a TTL of zero or a fragment does not fail the parse. Since 13.0.0 InternetError and the error of each protocol derive Clone, PartialEq, Eq and Hash, which lets PacketFlow carry them and keep its own derives.
The PTP arm is the one place where the parser's error is read before being wrapped. A versionPTP other than 1 or 2, or a reserved messageType, is UnsupportedProtocol: a revision of IEEE 1588 or a vendor's use the crate does not know, which is how every 0x88F7 frame came out before 11.5.0, not a corruption. A truncated or inconsistent message is InternetError::PtpError, and corrupted.error displays PTP error: …. The GOOSE and LLDP arms have no such case: every error of their decoders is a corruption.
The PROFINET arm changed in 11.6.0 (#133): it called the DCP decoder on every frame, and now calls profinet::validate_frame, which accepts any assigned Frame ID and decodes DCP only behind a DCP Frame ID; see the Profinet page.
Internet::try_from(&[u8]) (the probing version) still exists for callers that only have raw L3 bytes, but PacketFlow never uses it. It returns EmptyPacket for an empty slice, then tries, in this order:
- ARP, IPv4, IPv6, each with its
TryFrom; - Profinet, but only a complete DCP message: two bytes of a plausible Frame ID are no proof, so a cyclic frame is not recognized;
- GOOSE (since 11.6.0): a
lengththat covers the bytes exactly, and a complete goosePdu with its mandatory fields; - LLDP (since 11.6.0): beyond its decode, an LLDPDU that ends with an End of LLDPDU TLV, followed by zero padding only.
When all of them fail, it returns UnsupportedProtocol, and the reason each parser gave is lost, which is exactly the ambiguity described above. PTP is not probed. A probe that succeeds is a guess, not a verdict. Measured on the captures of pcaps_exemple/ at 11.6.0, the GOOSE and LLDP probes fire on GOOSE and LLDP frames only, but the PROFINET one takes 119 IS-IS frames of The-Ultimate-PCAP.pcapng for DCP: the LLC header of IS-IS, FE FE 03, reads as the Frame ID of a DCP Identify request (tested):
#![allow(unused)] fn main() { #[test] fn the_blind_probe_is_a_guess_not_a_verdict() { // Frame 24183 of The-Ultimate-PCAP.pcapng: IS-IS over LLC in an // 802.3br express mPacket. Its length field (0x0076) is no EtherType: // nothing is announced, so the pipeline parses nothing above. let raw = hex::decode(ISIS_OVER_LLC_MPACKET_HEX).unwrap(); let flow = parse(LinkType::IEEE802_3BR, &raw).unwrap(); assert_eq!(flow.data_link.network_protocol(), NetworkProtocol::Other(0x0076)); assert!(flow.internet.is_none() && flow.corrupted.is_none()); // Probed without that context, the same bytes pass for PROFINET: the // LLC header FE FE 03 reads as the Frame ID of a DCP Identify // request, a Get service, and a DCP header that holds. let payload = flow.data_link.network_payload(); assert_eq!(&payload[..3], [0xfe, 0xfe, 0x03]); let probed = Internet::try_from(payload).unwrap(); assert_eq!(probed.protocol_name, "Profinet"); let dcp = ProfinetPacket::try_from(payload).unwrap(); assert_eq!(dcp.frame_id, FrameId::IdentifyReq); assert_eq!(dcp.service_id, 3); // Get // A cyclic PROFINET frame, the reverse: valid by its Frame ID, but // two bytes are no proof, and the probe does not recognize it. let raw = hex::decode(PROFINET_RT_CLASS_1_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert!(Internet::try_from(flow.data_link.network_payload()).is_err()); } }
The protocols
Each protocol of this layer has its page: IPv4, IPv6, ARP, Profinet, and, since 11.6.0, GOOSE and LLDP.
NetworkProtocol | EtherType | protocol_name | Addresses | details |
|---|---|---|---|---|
Ipv4 | 0x0800 | "IPv4" | IPv4 | Ipv4(Ipv4Packet) |
Ipv6 | 0x86DD | "IPv6" | IPv6 | Ipv6(Ipv6Packet) |
Arp | 0x0806 | "ARP" | sender and target protocol addresses | Arp(ArpPacket) |
Profinet | 0x8892 | "Profinet" | none | None |
Ptp | 0x88F7 | "PTP" | none | Ptp(PtpPacket) |
Goose | 0x88B8 | "GOOSE" | none | Goose(GoosePacket) |
Lldp | 0x88CC | "LLDP" | none | Lldp(LldpPacket) |
PTP over raw Ethernet (EtherType 0x88F7, since 11.5.0) lands here too: protocol_name is "PTP", there are no addresses, payload_protocol is None, and the decoded message is in InternetDetails::Ptp. Its page, PTP, is under Application, where its module lives and where its UDP form is labelled. GOOSE and LLDP follow the same model, and their modules live with the internet protocols, parse::internet::protocols::goose and ::lldp.
IP-level tunnels
GRE (protocol 47) and IP-in-IP (protocols 4 and 41) are detected (#15) from Internet::payload_protocol and Internet::payload, not from the transport layer, because they have none: the Transport the pipeline builds for them is the catch-all one (protocol only, no ports, no payload). This IP-level check is the first step of the L7 stage, before the UDP-based tunnels and the application probes. Since it reads payload_protocol, a tunnel carried in IP fragments is not peeled. See the tunnels chapter.
IPv4
Announced by EtherType 0x0800 (or, inside a PPPoE session, by the PPP protocol 0x0021), or directly by a RAW IP capture, and parsed by the internet layer.
The Protocol byte plays the part the EtherType played one layer down: the internet layer does not parse what follows, it turns 6 into payload_protocol: Some(Tcp), the announcement the transport layer dispatches on (None for a fragment, see below). The bytes are those of a typical Linux TCP SYN, and the struct shows what Internet::try_from_network_parts returns for them.
| Bytes | Field | Check | Error |
|---|---|---|---|
| 0–19 | Fixed header | the buffer holds at least 20 bytes | Ipv4Error::InvalidLength |
| 0, high nibble | Version | 4 | InvalidVersion |
| 0, low nibble | IHL | IHL × 4 is between 20 and 60 bytes (IHL 5 to 15) | InvalidHeaderLength |
0–IHL × 4 | Header and options | the buffer holds the whole header | InvalidLength |
| 2–3 | Total length | at least the header length and at most the buffer length; 0 is the one exception, see TSO | InvalidTotalLength |
The payload is data[header_len..total_length]: Ethernet padding after a short IP packet is not handed to the transport layer.
The upper bound has a consequence: a packet cut by the capture's snapshot length fails it and is reported in corrupted, although nothing was wrong on the wire. parse receives the captured bytes only, so a truncated capture and a lying header look the same.
Options are neither decoded nor validated: Ipv4Packet::options holds their raw bytes, data[20..header_len], empty when IHL is 5.
The header checksum is not verified here: on a sender-side capture with hardware offloading it is often uncomputed, and a mandatory check would reject perfectly healthy traffic. packet_parser::checksum::verify_ipv4_header_checksum(&[u8]) -> Option<bool> is available when the context allows it: give it the IP packet, it returns None when the header itself is unreadable.
The rest of the header is reached through details (InternetDetails::Ipv4): ttl, identification, protocol, header_checksum, and typed accessors. dscp() returns a Dscp that displays its IANA name when it has one (EF (46), AF41 (34)), ecn() an Ecn (NotEct, Ect1, Ect0, Ce, RFC 3168). Both types come from the dscp_ecn module that Ipv6Packet shares for its Traffic Class.
A total length of zero: TSO
A host that hands TCP segmentation to its network card (TSO, LSO on Windows) gives the card one large packet, and a capture taken on that host sees it before the card cuts it, with a total length the stack has left at 0. Up to 11.5.0 such a packet failed the total length check and the internet layer was reported corrupted (#168). Like tshark with ip.tso_support, on by default, the crate now reads a total length of 0 as "up to the end of the frame":
#![allow(unused)] fn main() { pub fn validate_ipv4_total_length( total_length: u16, header_len: usize, data_len: usize, ) -> Result<(), Ipv4Error> { if total_length == 0 { return Ok(()); } let total_length = total_length as usize; if total_length < header_len || total_length > data_len { return Err(Ipv4Error::InvalidTotalLength { expected: total_length, actual: data_len, min_header_len: header_len, }); } Ok(()) } }
The payload is then data[header_len..], and Ipv4Packet::total_length keeps the wire value, 0, so a consumer can still tell such a packet apart. Any other value below the header length is still InvalidTotalLength. With nothing but the frame to bound it, the packet takes whatever follows it in the frame.
The golden test tests/ipv4_tso.rs checks two such frames: frame 275 of pcaps_exemple/protocols/ntp/ndpi_line.pcap, a TLS record of 3 133 bytes, and frame 47 790 of pcaps_exemple/The-Ultimate-PCAP.pcapng, a 1 908-byte TLS record carrying a ClientHello; both come out "TLS". The second one (tested):
#![allow(unused)] fn main() { #[test] fn a_total_length_of_zero_runs_to_the_end_of_the_frame() { // Frame 47 790 of The-Ultimate-PCAP.pcapng: a TLS ClientHello captured // on the sending host before its network card segmented it (TSO). let raw = hex::decode(IPV4_TSO_TLS_CLIENT_HELLO_HEX).unwrap(); assert_eq!(raw.len(), 1967); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert!(flow.corrupted.is_none()); // InvalidTotalLength before 11.6.0 let internet = flow.internet.as_ref().expect("IPv4"); let Some(InternetDetails::Ipv4(ipv4)) = &internet.details else { panic!("expected the IPv4 header in details"); }; assert_eq!(ipv4.total_length, 0); // the wire value, kept assert_eq!(ipv4.payload, &raw[14 + 20..]); // up to the end of the frame let transport = flow.transport.as_ref().expect("TCP"); assert_eq!(transport.destination_port, Some(443)); assert_eq!(transport.payload.map(<[u8]>::len), Some(1913)); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "TLS"); } }
Fragments
The crate does no IP reassembly. For a fragmented IPv4 packet (MF flag set or non-zero offset), payload_protocol is set to None so the transport layer is not parsed from incomplete data: a TCP header read from the second fragment of a datagram would be garbage with valid-looking ports. The first fragment is skipped too, although it does start with the L4 header: a UDP length field covers the whole datagram, so UDP's exact-length check would report a healthy fragment as corrupt, and the application probes would see a cut payload. The cost is that a fragmented packet has no transport and no ports. Ipv4Packet::is_fragmented(), more_fragments(), fragment_offset() and is_non_initial_fragment() expose the flags through details.
IPv6
Announced by EtherType 0x86DD, or directly by a RAW IP capture, and parsed by the internet layer.
The same SYN as in the IPv4 page, carried by IPv6 behind one Hop-by-Hop extension header. The fixed header is 40 bytes, and its Next header byte does not name the transport here: it says 0, an extension. The addresses and the payload come out as for IPv4; payload_protocol comes from the end of the chain, and details keeps the chain's bytes.
| Bytes | Field | Check | Error |
|---|---|---|---|
| 0–39 | Fixed header | the buffer holds at least 40 bytes | Ipv6Error::InvalidLength |
| 0, high nibble | Version | 6 | InvalidVersion |
| 4–5 | Payload length | the buffer holds 40 + payload_length bytes | InvalidPayloadLength |
| 40– | Extension chain | every extension header walked fits in the payload | InvalidExtensionHeader |
Bytes beyond the payload length (Ethernet padding) are not handed up, as for IPv4.
Extension headers are walked (RFC 8200 §4) to find the real transport protocol: Ipv6Packet::transport_protocol is the next header after the extension chain, extension_headers keeps the raw bytes of the chain, payload starts after it, and next_header keeps the fixed header's value, which may name an extension. Five types are walked: Hop-by-Hop (0), Routing (43) and Destination Options (60), whose length counts 8-byte units after the first 8; Fragment (44), a fixed 8 bytes; and AH (51), whose length counts 4-byte units minus 2 (RFC 4302). Any other value ends the walk and becomes transport_protocol: ESP (50), whose contents are encrypted, and the Mobility (135), HIP (139) and Shim6 (140) headers included.
As for IPv4, a Fragment extension header (or a No Next Header value, 59) sets transport_protocol to None, so nothing is parsed above an incomplete datagram; Ipv6Packet::is_fragmented() tells the two cases apart.
ARP
Announced by EtherType 0x0806, and parsed by the internet layer. ARP (RFC 826) maps a protocol address to a hardware address: who has 192.168.0.1? It has no transport, no payload, and nothing above it; what it has is two protocol addresses, and those are worth a flow identity.
The frame
The message is 28 bytes for IPv4 over Ethernet: four bytes that describe the address formats (hardware type 1 for Ethernet, protocol type 0x0800 for IPv4, then the two address lengths, 6 and 4), the operation (1 request, 2 reply), and two pairs of addresses, sender then target. In a request the target hardware address is the question: it is sent as zeros.
ArpPacket keeps every field as it is on the wire: hardware_type, protocol_type, hardware_len, protocol_len, operation, the two hardware addresses as [u8; 6] and the two protocol addresses as IpAddr. It is reached through details (InternetDetails::Arp).
What the internet layer keeps
ARP gets the same Internet struct as IPv4 and IPv6, so an ARP frame takes part in a flow table like any other packet:
sourceanddestinationare the sender and target protocol addresses, classified byIpTypelike any IP address (192.168.0.114isPrivate; the0.0.0.0of an ARP probe isUnknown);protocol_nameis"ARP";payload_protocolisNoneandpayloadis empty: nothing is parsed above,transportandapplicationstayNone;detailsholds theArpPacket, with the hardware addresses the flow identity does not carry.
The three frames come from the captures under pcaps_exemple/protocols/arp/ (Chris Sanders' public set). The reply is the request with source and destination swapped, as for any conversation; the data link layer tells the broadcast from the unicast answer. A gratuitous ARP names itself: sender and target protocol addresses are the same host, announcing its own address.
The parser keeps no cache and takes no view on what a frame means: a reply nobody asked for, or two hardware addresses answering for the same protocol address, are things a consumer sees by keying a table on (source, details.sender_hardware_addr). In arppoison.pcapng, that table shows one hardware address, 00:25:b3:bf:91:ee, claiming both 172.16.0.1 and 172.16.0.105.
Validations
| Bytes | Field | Check | Error |
|---|---|---|---|
| 0–27 | Message | the buffer holds at least 28 bytes | ArpError::InvalidLength |
| 0–1 | Hardware type | 1, Ethernet | UnsupportedHardwareType |
| 2–3 | Protocol type | IPv4 (0x0800) or IPv6 (0x86DD) | UnsupportedProtocolType |
| 4 | Hardware length | 6 | InvalidHardwareLength |
| 0– | Message | the buffer holds 8 + 2 × hardware length + 2 × protocol length bytes | InvalidLength, with that expected size |
| 5 | Protocol length | 4 for IPv4, 16 for IPv6 | InvalidProtocolLength |
| 6–7 | Operation | 1 (request) or 2 (reply) | UnsupportedOperation |
The rows are in the order of the checks.
Bytes past the message are ignored: the reply above is 46 bytes on the wire, four more than the request, and the gratuitous frame is padded to the 60-byte Ethernet minimum; neither changes the result. Since the EtherType said ARP, a failed check is reported in corrupted (layer: Internet, error: "ARP error: Invalid ARP packet length: expected at least 28 bytes, got 27 bytes"), not dropped.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- Only requests and replies. Inverse ARP (operations 8 and 9) travels under the same EtherType and comes out
corruptedwithUnsupported ARP operation: 8. RARP never reaches this parser: it has its own EtherType,0x8035. - Only Ethernet addresses. Hardware type 1 and 6-byte hardware addresses; a frame for another link type is
corrupted. - IPv6 over ARP is accepted (protocol type
0x86DD, 16-byte addresses), although IPv6 resolves addresses with Neighbor Discovery, decoded in the ICMPv6 page. - No cache, no detection: see above.
Profinet
Announced by EtherType 0x8892, and checked by the internet layer. PROFINET is the industrial Ethernet of Siemens and the PROFIBUS & PROFINET International group (IEC 61158): cyclic I/O data, alarms, clock synchronization (PTCP) and a discovery protocol, DCP, all carried directly in Ethernet frames, without IP. Every real-time frame starts with a two-byte Frame ID, whose range says what the frame carries. Since 11.6.0, the internet layer accepts every assigned Frame ID (#133) and decodes a DCP message block by block (#141), both fixed by #142 on a corpus of real captures (#140). The module is packet_parser::parse::internet::protocols::profinet.
What the internet layer checks: validate_frame
The internet dispatch has one arm for the EtherType:
#![allow(unused)] fn main() { NetworkProtocol::Profinet => { // Every RT frame is valid by its Frame ID; only a DCP Frame ID must // carry a readable DCP message (#133). profinet::validate_frame(payload)?; Ok(Self::profinet()) } }
and validate_frame, new in 11.6.0, works on two levels:
#![allow(unused)] fn main() { pub fn validate_frame(data: &[u8]) -> Result<FrameId, ProfinetPacketError> { let frame_id = validate_frame_id(data)?; if frame_id.is_dcp() { ProfinetPacket::try_from(data)?; } Ok(frame_id) } }
The Frame ID must be assigned, otherwise UnknownFrameId, and a payload of fewer than two bytes is FrameTooShort. A DCP Frame ID must, in addition, carry a DCP message that decodes. Cyclic data, alarms, PTCP and fragments are valid by their Frame ID alone: nothing past the first two bytes is read. A failure is reported in corrupted (layer: Internet), since the EtherType said PROFINET, with a text that starts with Profinet error: .
A PROFINET frame has no network addresses, and the crate gives it none: the Internet built by the private Internet::profinet() has protocol_name: "Profinet", source and destination None, no payload_protocol, an empty payload and details: None. InternetDetails has no PROFINET variant: the FrameId that validate_frame returns is dropped, and nothing is parsed above. The flow identity of a PROFINET frame is therefore its data link layer: for the Identify request drawn here, the station's MAC address and the PROFINET multicast address 01:0e:cf:00:00:00, which display_with_oui() prints as PnMc:00:00:00, the one multicast prefix of the crate's OUI table. A caller who wants the class of the frame or the DCP fields runs validate_frame or ProfinetPacket::try_from again on flow.data_link.network_payload().
Four real frames, cyclic data and an alarm under a VLAN tag, a PTCP delay request and a fragment, all four corrupted in 11.5.0 (tested):
#![allow(unused)] fn main() { #[test] fn every_rt_frame_is_valid_by_its_frame_id() { // Four real frames that 11.5.0 reported as corrupted. let frames = [ (PROFINET_RT_CLASS_1_HEX, 0x8000, FrameId::RtClass1Unicast), // cyclic data, VLAN 0 (PROFINET_ALARM_HEX, 0xFE01, FrameId::AlarmLow), (PROFINET_PTCP_DELAY_HEX, 0xFF40, FrameId::PtcpDelay), (PROFINET_FRAGMENT_HEX, 0xFF83, FrameId::Fragment), ]; for (frame, frame_id, class) in frames { let raw = hex::decode(frame).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.data_link.network_protocol(), NetworkProtocol::Profinet); let internet = flow.internet.as_ref().unwrap(); assert_eq!(internet.protocol_name, "Profinet"); assert!(internet.source.is_none() && internet.details.is_none()); assert!(flow.transport.is_none() && flow.corrupted.is_none()); // What the internet layer checked: the Frame ID and its class. let payload = flow.data_link.network_payload(); assert_eq!(validate_frame(payload), Ok(class)); // Not a DCP frame: the DCP decoder does not apply, and says so. assert_eq!( ProfinetPacket::try_from(payload), Err(ProfinetPacketError::NotDcp(frame_id)) ); } } }
Frame IDs: FrameId
FrameId::from_u16, public since 11.6.0, classes a Frame ID by its range, and returns None for a reserved value. The ranges are those of the pn_rt dissector of Wireshark, time-aware mode excluded:
| Frame ID | FrameId | Carries |
|---|---|---|
0x0020–0x0021, 0x0080–0x0081 | Sync | PTCP RTSync, with and without Follow Up |
0x0100–0x0FFF | RtClass3 | RT_CLASS_3 cyclic data (IRT) |
0x8000–0xBBFF | RtClass1Unicast | RT_CLASS_1 cyclic data, unicast |
0xBC00–0xBFFF | RtClass1Multicast | RT_CLASS_1 cyclic data, multicast |
0xC000–0xF7FF | Unicast | RT_CLASS_1 / RT_CLASS_UDP cyclic data, unicast |
0xF800–0xFBFF | Multicast | RT_CLASS_1 / RT_CLASS_UDP cyclic data, multicast |
0xFC01, 0xFC41 | AlarmHigh | high-priority alarm, 0xFC41 with security |
0xFE01, 0xFE41 | AlarmLow | low-priority alarm, 0xFE41 with security |
0xFE02, 0xFE42 | Rsi | Remote Service Interface, 0xFE42 with security |
0xFE03 | Sxp | SXP via RTAv3 |
0xFEFC | Hello | DCP Hello |
0xFEFD | GetReqSetReqGetRespSetResp | DCP Get or Set, request or response |
0xFEFE | IdentifyReq | DCP Identify request |
0xFEFF | IdentifyResp | DCP Identify response |
0xFF00–0xFF01 | PtcpAnnounce | PTCP Announce |
0xFF20–0xFF21 | PtcpFollowUp | PTCP Follow Up |
0xFF40–0xFF43 | PtcpDelay | PTCP Delay, request and responses |
0xFF80–0xFF8F | Fragment | a fragment of an RT frame |
| anything else | — | reserved: UnknownFrameId |
FrameId is #[repr(u16)], each discriminant the start of its range, and #[non_exhaustive]. 11.5.0 had the five variants Unicast, Multicast, GetReqSetReqGetRespSetResp, IdentifyReq and IdentifyResp; the thirteen others were added at the end of the enum. is_dcp() is true for the four DCP Frame IDs, Hello and the three after it in the table: those frames carry a message that ProfinetPacket decodes.
DCP: ProfinetPacket
#![allow(unused)] fn main() { pub struct ProfinetPacket<'a> { pub frame_id: FrameId, pub service_id: u8, pub service_type: u8, pub xid: u32, pub response_delay: u16, pub dcp_data_length: u16, pub option: u8, // of the first block, 0 without block: pub suboption: u8, // the three are kept for compatibility, pub dcp_block_length: u16, // `blocks` holds every block pub name_of_station: &'a str, // from the block option 2 / suboption 2, empty without one pub blocks: Vec<DcpBlock<'a>>, // every block, in message order } }
The fixed header is 12 bytes; DCPDataLength counts the blocks that follow, and bytes past it, the Ethernet padding among them, are ignored:
| Bytes | Field | Note |
|---|---|---|
| 0–1 | frame_id | one of the four DCP Frame IDs; another assigned one is NotDcp, a reserved one UnknownFrameId |
| 2 | service_id | DCP_SERVICE_GET (3), DCP_SERVICE_SET (4), DCP_SERVICE_IDENTIFY (5), DCP_SERVICE_HELLO (6); the value is not checked |
| 3 | service_type | DCP_SERVICE_TYPE_REQUEST (0) for a request; any other value is read as a response, 1 for success, 5 for not supported |
| 4–7 | xid | transaction ID |
| 8–9 | response_delay | |
| 10–11 | dcp_data_length | the bytes of blocks; beyond the frame, DcpDataOverflow |
Then come the blocks, each a 4-byte header and its data:
#![allow(unused)] fn main() { pub struct DcpBlock<'a> { pub option: u8, pub suboption: u8, pub block_length: u16, // DCPBlockLength as announced, qualifier included pub qualifier: Option<u16>, // BlockInfo or BlockQualifier, None when the service has none pub data: &'a [u8], // the block after its qualifier } }
| Bytes | Field | Note |
|---|---|---|
| 0 | option | |
| 1 | suboption | |
| 2–3 | block_length | beyond the blocks, DcpBlockOverflow |
| 4–5 | qualifier | only when the service has one; a block too short for it is DcpBlockTooShort |
| … | data | |
| one padding byte | after a block of odd length, counted in DCPDataLength, in neither data nor block_length |
Whether a block starts with a qualifier depends on the service, as the pn_dcp dissector of Wireshark reads it: a BlockInfo in the responses to Identify and Get and in a Hello request, a BlockQualifier in a Set request, nothing elsewhere, the filter of an Identify request or a Set response for instance. A sender that leaves out the padding byte after the last block is not refused.
name_of_station comes from the first block that is_name_of_station() recognizes, option 2 / suboption 2, wherever it is in the message: read up to its first NUL byte, as tshark does, and UTF-8, otherwise InvalidNameOfStation. The whole block stays in its DcpBlock::data. The bug-report capture of the corpus, iti_profinet-wireshark-bug.pcap, names its station %n%n%n followed by zeros, and the name comes out as %n%n%n . The other blocks, IP parameters, device ID, role or options, keep their bytes as they are.
The Identify response and the Set request of iti_ChangeIPUsingDCP.pcap, the two frames of that capture that 11.5.0 refused (tested):
#![allow(unused)] fn main() { #[test] fn dcp_messages_are_decoded_block_by_block() { // Frame 2 of iti_ChangeIPUsingDCP.pcap: the Identify response of // X208-BORD. Its first block is DeviceOptions, not the name. let raw = hex::decode(PROFINET_DCP_IDENTIFY_RESPONSE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert!(flow.corrupted.is_none()); let dcp = ProfinetPacket::try_from(flow.data_link.network_payload()).unwrap(); assert_eq!(dcp.frame_id, FrameId::IdentifyResp); assert_eq!((dcp.service_id, dcp.service_type), (DCP_SERVICE_IDENTIFY, 1)); assert_eq!((dcp.xid, dcp.dcp_data_length), (0x0100_0001, 94)); let blocks: Vec<(u8, u8, u16)> = dcp .blocks .iter() .map(|block| (block.option, block.suboption, block.block_length)) .collect(); assert_eq!(blocks, [(2, 5, 28), (2, 1, 5), (2, 2, 11), (2, 3, 6), (2, 4, 4), (1, 2, 14)]); // In a response, each block starts with a BlockInfo, kept apart. assert_eq!(dcp.blocks[2].qualifier, Some(0)); assert_eq!(dcp.blocks[2].data, b"X208-BORD"); // 11 bytes, minus BlockInfo assert_eq!(dcp.name_of_station, "X208-BORD"); // taken from block 2/2 assert_eq!(dcp.blocks[5].qualifier, Some(1)); assert_eq!(dcp.blocks[5].data, [192, 168, 0, 6, 255, 255, 255, 0, 192, 168, 0, 1]); // The fields kept for compatibility describe the first block. assert_eq!((dcp.option, dcp.suboption, dcp.dcp_block_length), (2, 5, 28)); // Frame 3: the Set request that gives it 192.168.0.10. A Set request // block starts with a BlockQualifier; the message carries no name. let raw = hex::decode(PROFINET_DCP_SET_REQUEST_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let dcp = ProfinetPacket::try_from(flow.data_link.network_payload()).unwrap(); assert_eq!(dcp.frame_id, FrameId::GetReqSetReqGetRespSetResp); assert_eq!((dcp.service_id, dcp.service_type), (DCP_SERVICE_SET, DCP_SERVICE_TYPE_REQUEST)); assert_eq!(dcp.blocks.len(), 1); assert_eq!((dcp.blocks[0].option, dcp.blocks[0].suboption), (1, 2)); assert_eq!(dcp.blocks[0].qualifier, Some(1)); assert_eq!(dcp.blocks[0].data, [192, 168, 0, 10, 255, 255, 255, 0, 192, 168, 0, 1]); assert_eq!(dcp.name_of_station, ""); } }
Validations
All of them are ProfinetPacketError, in packet_parser::errors::internet::profinet; the five after InvalidNameOfStation were added in 11.6.0, at the end of the enum:
| Error | When |
|---|---|
PacketTooShort(usize) | a DCP message shorter than its 12-byte header (16 bytes until 11.5.0) |
UnknownFrameId(u16) | a reserved Frame ID |
InvalidDcpBlockLength(usize) | fewer than 4 bytes left for the header of a block; since 11.6.0 nothing else |
InvalidNameOfStation | the NameOfStation block is not UTF-8 |
FrameTooShort(usize) | fewer than two bytes: no Frame ID |
NotDcp(u16) | ProfinetPacket::try_from on a Frame ID that is not DCP; validate_frame never returns it, so it never reaches corrupted |
DcpDataOverflow { declared, available } | DCPDataLength announces more than the bytes after the header |
DcpBlockOverflow { option, suboption, declared, available } | DCPBlockLength announces more than the blocks hold |
DcpBlockTooShort { option, suboption, declared, needed } | a block shorter than the BlockInfo or BlockQualifier its service imposes |
The one PN-RT frame of the corpus that stays corrupted, and that tshark calls malformed too (tested):
#![allow(unused)] fn main() { #[test] fn a_dcp_message_shorter_than_its_length_is_corrupted() { // Frame 3 of miguelob_pn_dcp.pcapng: DCPDataLength announces 4 bytes // of blocks, the frame ends 2 bytes later. tshark calls it malformed. let raw = hex::decode(PROFINET_DCP_SHORT_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert!(flow.internet.is_none()); let corrupted = flow.corrupted.unwrap(); assert_eq!(corrupted.layer, CorruptedLayerKind::Internet); assert_eq!( corrupted.error.to_string(), "Profinet error: DCP data length 4 exceeds the 2 bytes after the header" ); assert_eq!( validate_frame(flow.data_link.network_payload()), Err(ProfinetPacketError::DcpDataOverflow { declared: 4, available: 2 }) ); } }
The corpus: 232 PN-RT frames against tshark
The repository had no PROFINET capture until #140, which is how the defects of 11.5.0 stayed invisible. pcaps_exemple/protocols/profinet/ now holds seven real captures, 2 685 frames of which 232 are PN-RT for tshark (-Y pn_rt), from three documented sources: the CISA's icsnpp-profinet-io-cm (BSD-3-Clause), ITI's ICS-Security-Tools (CC-BY-4.0) and miguelob/ICS-Hacking (GPL-3.0).
| Capture | Frames | PN-RT | PROFINET content |
|---|---|---|---|
cisagov_profinet_io_cm_mixed_1.pcap | 1 635 | 164 | 102 cyclic 0xC000/0xC002, 41 PTCP 0xFF40, 18 Identify requests, 1 response, 2 alarms 0xFE01 |
cisagov_profinet_io_cm.pcap | 960 | 10 | 10 fragments, 0xFF83 to 0xFF8D |
iti_ChangeIPUsingDCP.pcap | 6 | 4 | Identify request and response, then Set request and response |
iti_PROFINET-RT.pcap | 14 | 14 | 14 Identify requests |
iti_profinet-wireshark-bug.pcap | 4 | 4 | an Identify and a Set exchange, VLAN-tagged |
miguelob_pn.pcapng | 48 | 18 | 10 cyclic RT_CLASS_1 0x8000/0x8010, 4 alarms 0xFE01, 4 DCP, all VLAN-tagged |
miguelob_pn_dcp.pcapng | 18 | 18 | 15 Identify responses, 3 Identify requests |
The golden test tests/profinet_corpus.rs compares every PN-RT frame with tshark 4.6.6, frozen in tests/data/profinet_tshark_oracle.tsv: the Frame ID, the service and the NameOfStation of every DCP message, and tshark's malformed flag. The crate must find exactly the PN-RT frames of tshark by their EtherType, VLAN tags included, class every Frame ID, read the same NameOfStation, and refuse only what tshark calls malformed. The outcome is frozen: 231 frames give internet = Profinet, and one is DcpDataOverflow, frame 3 of miguelob_pn_dcp.pcapng, the example above. The 11.5.0 validator gave 103 Profinet and 129 corrupted, almost all on healthy frames: 67 UnknownFrameId (cyclic RT_CLASS_1, PTCP, alarms, fragments), 56 InvalidDcpBlockLength (the cyclic 0xC000 frames, read as DCP; the 46 cyclic 0xC002 frames passed that reading), 5 InvalidNameOfStation (the first block read as the name) and 1 PacketTooShort.
The corpus covers eight classes of the table: Unicast, RtClass1Unicast, AlarmLow, PtcpDelay, Fragment and the three DCP Frame IDs other than Hello. The ten others, Sync, RtClass3, RtClass1Multicast, Multicast, AlarmHigh, Rsi, Sxp, Hello, PtcpAnnounce and PtcpFollowUp, are covered by the crate's unit tests only. The fuzz target parse_profinet runs nightly on validate_frame and ProfinetPacket::try_from.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- The content of the frames: cyclic I/O data, alarms, PTCP and fragments are classed, not decoded, and fragments are not reassembled.
- DCP block values: only the NameOfStation is read; IP parameters, device ID, role and options stay raw in
DcpBlock::data. - No
details: a caller re-runsvalidate_frameorProfinetPacket::try_fromon the link payload. - The blind probe of
Internet::try_fromrecognizes PROFINET by a complete DCP message only: two bytes of Frame ID are not a proof, so a cyclic frame is not recognized without its EtherType, and a DCP-looking header can be something else (see the internet page). - PROFINET over UDP is ordinary UDP to the crate: no rule of the dispatch table names RT_CLASS_UDP (UDP 34962 and 34963,
profinet-rtandprofinet-rtm), nor the DCE/RPC of PROFINET IO-CM (UDP 34964,profinet-cm), of which the corpus holds 1 000 datagrams. - Time-aware Frame IDs are not classed.
GOOSE
Generic Object Oriented Substation Event, IEC 61850-8-1, added in 11.6.0 (#160) with IEC 60870-5-104 and BACnet/IP, the remaining Tier 2 protocols of the epic #102: the events of an electrical substation, published by its IEDs in multicast, straight over Ethernet. Sampled Values, named with GOOSE in the epic, is not decoded: no redistributable capture was found. The module is packet_parser::parse::internet::protocols::goose.
On Ethernet, as the internet layer
GOOSE has no IP and no UDP. It is announced by EtherType 0x88B8, often under a VLAN tag that the link layer consumes, and, like PTP on 0x88F7, the frame is the internet layer. The link layer maps the EtherType to NetworkProtocol::Goose (added in 11.6.0, at the end of the enum), and the internet dispatch has one arm for it:
#![allow(unused)] fn main() { NetworkProtocol::Goose => Ok(Self::from_goose(GoosePacket::try_from(payload)?)), }
The flow gets an Internet with protocol_name "GOOSE", no addresses, payload_protocol None, an empty payload and the decoded frame in InternetDetails::Goose; transport and application stay None, and the golden histogram counts GOOSE frames as frames without application. There is no port and no Decode As: the EtherType decides. Nor is any error softened into "unsupported", as PTP does for an unknown version: the EtherType announced GOOSE, so every GooseParseError is a corrupted internet layer, InternetError::GooseError, whose text in corrupted starts with GOOSE error: .
In JSON, protocol_internet is "GOOSE". The data link changed too in 11.6.0: ethertype is "GOOSE" (Ethertype::static_name), where 11.5.0 wrote "Unknown (0x88B8)", and network_protocol is {"kind": "goose"}, where it was {"kind": "other", "value": 35000}.
Frame 1 of iti_GOOSE.pcap, a GE F650 relay, without VLAN tag (tested):
#![allow(unused)] fn main() { #[test] fn goose_is_an_internet_layer_that_keeps_its_pdu() { let raw = hex::decode(GOOSE_F650_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.data_link.network_protocol(), NetworkProtocol::Goose); // EtherType 0x88B8 right after the MAC addresses: no VLAN tag. let ethernet = flow.data_link.as_ethernet().unwrap(); assert!(ethernet.vlan.is_none()); // No IP, no UDP: the frame is the internet layer, without addresses, // and nothing is parsed above it. let internet = flow.internet.as_ref().unwrap(); assert_eq!(internet.protocol_name, "GOOSE"); assert!(internet.source.is_none() && internet.destination.is_none()); assert!(internet.payload_protocol.is_none() && internet.payload.is_empty()); assert!(flow.transport.is_none() && flow.application.is_none()); assert!(flow.corrupted.is_none()); let Some(InternetDetails::Goose(goose)) = &internet.details else { panic!("expected a decoded GOOSE frame in details"); }; assert_eq!((goose.app_id, goose.length), (0x0001, 145)); assert!(!goose.simulation_bit()); let pdu = &goose.pdu; assert_eq!(pdu.gocb_ref, "GEDeviceF650/LLN0$GO$gcb01"); assert_eq!(pdu.data_set, "GEDeviceF650/LLN0$GOOSE1"); assert_eq!(pdu.go_id, Some("F650_GOOSE1")); assert_eq!(pdu.time_allowed_to_live, 40_000); // milliseconds assert_eq!((pdu.st_num, pdu.sq_num), (1, 10)); assert_eq!((pdu.simulation, pdu.conf_rev, pdu.nds_com), (false, 1, false)); // tshark: Jan 2, 2000 02:46:11.258165836 UTC assert_eq!(pdu.timestamp.seconds, 946_781_171); assert_eq!(pdu.timestamp.nanoseconds(), 258_165_836); assert!(!pdu.timestamp.clock_not_synchronized()); // allData: eight values, a boolean then a bit string, four times. assert_eq!((pdu.num_dat_set_entries, pdu.all_data.len()), (8, 8)); assert_eq!(pdu.all_data[0].kind, Some(DataKind::Boolean)); assert_eq!(pdu.all_data[0].as_bool(), Some(false)); assert_eq!(pdu.all_data[1].kind, Some(DataKind::BitString)); assert_eq!(pdu.all_data[1].value, [0x03, 0x00, 0x00]); // 3 unused bits, then the bits assert_eq!(pdu.all_data[1].as_bool(), None); assert_eq!(pdu.security, None); } }
The frame: GoosePacket
#![allow(unused)] fn main() { pub struct GoosePacket<'a> { pub app_id: u16, pub length: u16, pub reserved1: u16, pub reserved2: u16, pub pdu: GoosePdu<'a>, } }
| Bytes | Field | Note |
|---|---|---|
| 0–1 | app_id | APPID |
| 2–3 | length | from the APPID to the end: it must be exactly the number of bytes after the EtherType |
| 4–5 | reserved1 | bit 15 is the simulation bit, read by simulation_bit() |
| 6–7 | reserved2 | |
| 8… | pdu | the goosePdu in BER, tag 0x61 ([APPLICATION 1], constructed) |
Since length covers the frame exactly, the goosePdu must end where the frame ends: bytes after it are UnexpectedTrailingBytes, a frame cut short no longer matches its length. GOOSE has no trailing slice like PTP's.
The goosePdu: GoosePdu
The PDU is a sequence of context-tagged BER elements. They are read in the order they come; a tag the PDU does not define is skipped, a mandatory field that never comes is MissingField(tag):
#![allow(unused)] fn main() { pub struct GoosePdu<'a> { pub gocb_ref: &'a str, // control block reference, LD/LLN0$GO$gcb pub time_allowed_to_live: u32, // ms before a subscriber holds the publisher for lost pub data_set: &'a str, pub go_id: Option<&'a str>, pub timestamp: UtcTime, pub st_num: u32, // state number: incremented at each change of the data pub sq_num: u32, // sequence number: incremented at each retransmission, // back to zero with the state pub simulation: bool, pub conf_rev: u32, pub nds_com: bool, // needs commissioning pub num_dat_set_entries: u32, pub all_data: Vec<GooseData<'a>>, pub security: Option<&'a [u8]>, // edition 2, as is } }
| Tag | Field | Decoded as | When absent |
|---|---|---|---|
0x80 | gocb_ref | &str | MissingField |
0x81 | time_allowed_to_live | u32 | MissingField |
0x82 | data_set | &str | MissingField |
0x83 | go_id | &str | None |
0x84 | timestamp | UtcTime, exactly 8 bytes | MissingField |
0x85 | st_num | u32 | MissingField |
0x86 | sq_num | u32 | MissingField |
0x87 | simulation | bool, exactly 1 byte | false |
0x88 | conf_rev | u32 | MissingField |
0x89 | nds_com | bool, exactly 1 byte | false |
0x8A | num_dat_set_entries | u32 | MissingField |
0xAB | all_data | Vec<GooseData> | MissingField |
0x8C | security | raw bytes | None |
BER lengths are read in the short form and in the long form of one to four length octets. The integers are read as u32: one to four bytes, or five whose first is zero, which is how the simulator of iti_GOOSE_DEMO.pcap writes all of them. The strings borrow the frame; if their bytes are not UTF-8, the string stops before the first invalid one.
The timestamp is the UtcTime of §8.1.3.7:
#![allow(unused)] fn main() { pub struct UtcTime { pub seconds: u32, // since 1970 pub fraction: u32, // of a second, in 1/2^24 pub quality: u8, // bit 7 leap second known, 6 clock failure, // 5 clock not synchronized, 0–4 accuracy } }
leap_second_known(), clock_failure() and clock_not_synchronized() read the quality bits, and nanoseconds() converts the fraction, rounded down: 258 165 836 for the F650 frame, the value tshark prints.
allData: GooseData
all_data keeps each value of the data set as BER gave it:
#![allow(unused)] fn main() { pub struct GooseData<'a> { pub tag: u8, pub kind: Option<DataKind>, pub value: &'a [u8], } }
kind names the choice of the Data type from the number of the tag (tag & 0x1F): 1 Array, 2 Structure, 3 Boolean, 4 BitString, 5 Integer, 6 Unsigned, 7 FloatingPoint, 9 OctetString, 10 VisibleString, 11 GeneralizedTime, 12 BinaryTime, 13 Bcd, 14 BooleanArray, 15 ObjId, 16 MmsString, 17 UtcTime; any other number is None. The value stays raw, an array or a structure keeps its encoded elements in value, and the one accessor is as_bool(), for a boolean of one byte. The number of elements is not compared with num_dat_set_entries.
Validations
All of them are GooseParseError, in packet_parser::errors::internet::goose:
| Error | When |
|---|---|
Truncated { expected, actual } | fewer than 10 bytes: the header, the PDU tag and one length byte |
LengthMismatch { declared, actual } | length is not the number of bytes after the EtherType |
InvalidPduTag(u8) | the PDU does not start with 0x61 |
InvalidBerLength(usize) | at that offset, a BER length cut short, in the indefinite form, or of more than four octets |
ElementOverflow { tag, declared, available } | an element declares more bytes than remain |
UnexpectedTrailingBytes(usize) | bytes after the goosePdu |
IntegerTooLong { tag, length } | an integer field of zero bytes, or of more than four, unless it is a zero followed by four |
InvalidBoolean { tag, length } | simulation or nds_com not on one byte |
InvalidTimestamp(usize) | a timestamp not on eight bytes |
MissingField(u8) | a mandatory field, named by its tag |
The simulator frame, under its VLAN tag, in JSON, probed without its EtherType, then cut by one byte (tested):
#![allow(unused)] fn main() { #[test] fn goose_under_a_vlan_tag_probed_blindly_and_cut_short() { // Frame 1 of iti_GOOSE_DEMO.pcap: the link layer consumes the VLAN // tag, and the EtherType it hands over is GOOSE's. let raw = hex::decode(GOOSE_DEMO_VLAN_10_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let vlan = flow.data_link.as_ethernet().and_then(|ethernet| ethernet.vlan.as_ref()); assert_eq!(vlan.map(|tag| tag.id), Some(10)); assert_eq!(flow.data_link.network_protocol(), NetworkProtocol::Goose); let internet = flow.internet.as_ref().unwrap(); let Some(InternetDetails::Goose(goose)) = &internet.details else { panic!("expected a decoded GOOSE frame in details"); }; assert_eq!(goose.app_id, 0x2000); let pdu = &goose.pdu; assert_eq!((pdu.gocb_ref, pdu.data_set, pdu.go_id), ("111", "222", Some("333"))); // Its integers take five bytes, a zero then four: 00 00 00 27 10. assert_eq!(pdu.time_allowed_to_live, 10_000); assert_eq!((pdu.num_dat_set_entries, pdu.all_data.len()), (10, 10)); assert!(pdu.all_data.iter().all(|value| value.as_bool() == Some(false))); // In JSON, the flow names the internet layer and the EtherType. let json = serde_json::to_value(flow.to_owned_flow()).unwrap(); assert_eq!(json["protocol_internet"], "GOOSE"); assert_eq!(json["data_link"]["network_protocol"]["kind"], "goose"); assert_eq!(json["data_link"]["link_details"]["ethertype"], "GOOSE"); assert!(json["source_ip"].is_null()); // Without the EtherType, the probing Internet::try_from finds it too. let probed = Internet::try_from(flow.data_link.network_payload()).unwrap(); assert_eq!(probed.protocol_name, "GOOSE"); // One byte short, the Length field no longer covers the frame: the // EtherType announced GOOSE, so the internet layer is corrupted. let flow = parse(LinkType::ETHERNET, &raw[..raw.len() - 1]).unwrap(); assert!(flow.internet.is_none()); let corrupted = flow.corrupted.unwrap(); assert_eq!(corrupted.layer, CorruptedLayerKind::Internet); assert_eq!( corrupted.error.to_string(), "GOOSE error: GOOSE length 108 does not match the 107 bytes after the EtherType" ); } }
The blind probe
Internet::try_from, the probing parser for callers without an EtherType, tries GOOSE after ARP, IPv4, IPv6 and Profinet (see the internet page). The proof is the length that covers the bytes exactly and a goosePdu complete with its mandatory fields. The golden test runs the probe on every GOOSE frame of the corpus and gets the same packet back; on the frames of the other folders of pcaps_exemple/protocols/, neither the EtherType nor the probe gives GOOSE.
Oracle: 494 frames, field by field
The golden test tests/goose_golden.rs runs the four captures of pcaps_exemple/protocols/goose/ and compares every GOOSE frame with tshark 4.6.6, frozen in tests/data/goose_tshark_oracle.tsv by tools/goose_oracle.sh: VLAN, APPID, length, reserved words, gocbRef, timeAllowedtoLive, datSet, goID, stNum, sqNum, simulation, confRev, ndsCom, numDatSetEntries, and the number and types of the allData elements. The crate recognizes exactly the frames tshark sees, 452 of them under a VLAN tag that the link layer removed. The fuzz target parse_goose runs nightly on the decoder, seeded with the two frames of the examples.
| Capture | GOOSE frames | Publisher | VLAN |
|---|---|---|---|
iti_GOOSE.pcap | 8 | a GE F650 relay, GEDeviceF650/LLN0$GO$gcb01 | none |
iti_GOOSE_DEMO.pcap | 1 | a simulator, APPID 0x2000, ten booleans | 10 |
iti_Sample_File_GOOSE.pcap | 451 | three IEDs of a substation, AA1C1Q01A1LD0, AA1C1Q05A1LD0 and AA1C1Q07A1LD0, 25 entries per message | 0 |
iti_Sample_File_MMS_and_GOOSE.pcap | 34 of 301 | the same IEDs, among MMS, NTP and TCP | none |
The four come from the ICS-Security-Tools repository of ITI (CC-BY-4.0); pcaps_exemple/protocols/goose/SOURCE.md says why they are taken for real traffic. A second test follows the retransmission scheme on the substation capture: of the 448 transitions between two messages of the same IED, 250 are a change of state (stNum + 1, sqNum back to 0) and 198 a retransmission (sqNum + 1); none is a gap.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- Sampled Values (IEC 61850-9-2, EtherType
0x88BA) is not decoded: it maps toNetworkProtocol::Other(0x88BA), and the internet layer staysNone. - Only EtherType
0x88B8: no rule of the dispatch table recognizes GOOSE carried over UDP. - Values are not interpreted:
allDatakeeps tags and bytes; arrays and structures are not walked, a bit string keeps its unused-bits byte, floats and times are not converted. - No subscriber state: the crate does not follow
stNumandsqNumfrom one frame to the next, does not timetimeAllowedtoLiveout, and does not checkconfRevornumDatSetEntriesagainst a data set. One frame at a time, like the rest of the crate. - Security (
security, edition 2) is kept as is, not checked.
LLDP
Link Layer Discovery Protocol, IEEE 802.1AB, added in 11.6.0 (#178) under the epic of the ICS bench protocols, LLDP, S7CommPlus and MELSOFT (#177): every device announces to its direct neighbours, in multicast, who it is (chassis, port, name, description, capabilities, management addresses) and, through organization TLVs, what PROFINET, IEEE 802.1, IEEE 802.3 or LLDP-MED add to it. Until 11.6.0 its EtherType was only named. The module is packet_parser::parse::internet::protocols::lldp.
On Ethernet, as the internet layer
LLDP has no IP and no UDP. Its EtherType, 0x88CC, maps to NetworkProtocol::Lldp (added in 11.6.0 at the end of the enum, where 11.5.0 had Other(0x88CC)), and, as for GOOSE, the LLDPDU is the internet layer. The internet dispatch has one arm for it:
#![allow(unused)] fn main() { NetworkProtocol::Lldp => Ok(Self::from_lldp(LldpPacket::try_from(payload)?)), }
The flow gets an Internet with protocol_name "LLDP", no addresses, payload_protocol None, an empty payload and the decoded LLDPDU in InternetDetails::Lldp; transport and application stay None. The application label does not move, an LLDP frame had none and has none, so the golden histogram is unchanged; what the frame gains is an internet layer, protocol_internet "LLDP" in JSON, and a network_protocol of {"kind": "lldp"} where it was {"kind": "other", "value": 35020}. The EtherType was already named "LLDP". Every LldpParseError is a corrupted internet layer, InternetError::LldpError, whose text in corrupted starts with LLDP error: .
The LLDPDU is what the link layer hands over after the EtherType: 59 LLDP frames of the corpus are IEEE 802.3br express mPackets, and the decoder sees them without their mCRC.
Frame 29 of cisagov_profinet_io_cm_mixed_1.pcap, a Siemens SCALANCE X208 switch (tested):
#![allow(unused)] fn main() { #[test] fn lldp_keeps_every_tlv_and_reads_the_announcement() { // Frame 29 of cisagov_profinet_io_cm_mixed_1.pcap: a Siemens // SCALANCE X208 switch announces itself on EtherType 0x88CC. let raw = hex::decode(LLDP_SCALANCE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.data_link.network_protocol(), NetworkProtocol::Lldp); let internet = flow.internet.as_ref().unwrap(); assert_eq!(internet.protocol_name, "LLDP"); assert!(internet.source.is_none() && internet.payload_protocol.is_none()); assert!(flow.transport.is_none() && flow.application.is_none()); assert!(flow.corrupted.is_none()); let Some(InternetDetails::Lldp(lldp)) = &internet.details else { panic!("expected a decoded LLDPDU in details"); }; // Every TLV in wire order, End of LLDPDU included; nothing after it. let types: Vec<u8> = lldp.tlvs.iter().map(|tlv| tlv.tlv_type).collect(); assert_eq!(types, [1, 2, 3, 6, 7, 8, 127, 127, 127, 0]); assert_eq!(lldp.tlvs[3].type_name(), "System Description"); assert!(lldp.padding.is_empty()); // The three mandatory TLVs: chassis and port IDs locally assigned // (subtype 7), readable as text, and the time to live in seconds. assert_eq!(lldp.chassis_id.subtype, 7); assert_eq!(lldp.chassis_id.as_text(), Some("siemens-x208-switch")); assert_eq!((lldp.port_id.subtype, lldp.port_id.as_text()), (7, Some("port-004"))); assert_eq!(lldp.time_to_live, 20); // The optional TLVs, through accessors. assert_eq!(lldp.system_name(), None); assert_eq!( lldp.system_description(), Some("Siemens AG SIMATIC S7 MULTIPORT SCALANCE X 200 FAM") ); let capabilities = lldp.system_capabilities().unwrap(); assert_eq!(capabilities.capabilities, SystemCapabilities::STATION_ONLY); assert!(capabilities.is_enabled(SystemCapabilities::STATION_ONLY)); let addresses: Vec<_> = lldp.management_addresses().collect(); assert_eq!(addresses.len(), 1); assert_eq!(addresses[0].ip(), Some(IpAddr::V4(Ipv4Addr::UNSPECIFIED))); // Interface numbering 2 (ifIndex), interface 4, and an 8-byte OID. assert_eq!((addresses[0].interface_subtype, addresses[0].interface_number), (2, 4)); assert_eq!(addresses[0].oid.len(), 8); let organizations: Vec<_> = lldp .organization_tlvs() .map(|tlv| (tlv.organization(), tlv.subtype)) .collect(); assert_eq!( organizations, [(Some("PROFINET"), 2), (Some("PROFINET"), 5), (Some("IEEE 802.3"), 1)] ); } }
The LLDPDU: LldpPacket
#![allow(unused)] fn main() { pub struct LldpPacket<'a> { pub chassis_id: LldpId<'a>, pub port_id: LldpId<'a>, pub time_to_live: u16, // seconds; 0 withdraws the device pub tlvs: Vec<LldpTlv<'a>>, // every TLV in wire order, the three mandatory // ones and End of LLDPDU included pub padding: &'a [u8], // after End of LLDPDU: the padding of a short frame } pub struct LldpTlv<'a> { pub tlv_type: u8, pub value: &'a [u8], } }
The LLDPDU is a run of TLVs, each a two-byte header, seven bits of type and nine of length, then the value, borrowed from the frame. It opens with Chassis ID, Port ID and Time To Live, in that order, and closes with End of LLDPDU. The decoder stops at that TLV, and what follows is padding, kept as is, not checked. Without an End TLV the TLVs run to the end of the frame and padding is empty. The 276 LLDPDUs of the corpus all end with an End TLV, and none has padding.
| Type | type_name() | Length accepted | Read by |
|---|---|---|---|
| 0 | End of LLDPDU | 0 | ends the LLDPDU |
| 1 | Chassis ID | 2 to 256 | chassis_id |
| 2 | Port ID | 2 to 256 | port_id |
| 3 | Time To Live | 2 | time_to_live |
| 4 | Port Description | any | port_description() |
| 5 | System Name | any | system_name() |
| 6 | System Description | any | system_description() |
| 7 | System Capabilities | 4 | system_capabilities() |
| 8 | Management Address | 9 to 167, tiled by its inner lengths | management_addresses() |
| 127 | Organizationally Specific | at least 4 | organization_tlvs() |
| 9 to 126 | Reserved | any | tlv(tlv_type) |
The three text accessors give the value of the first TLV of their type as &str when it is UTF-8, None otherwise; tlv(tlv_type) gives the first TLV of a type, raw, and LldpTlv::as_text() reads any value as text.
Chassis and port: LldpId
#![allow(unused)] fn main() { pub struct LldpId<'a> { pub subtype: u8, pub id: &'a [u8], } }
The first byte of the value is the subtype, which says what the ID is:
| Subtype | Chassis ID | Port ID |
|---|---|---|
| 1 | chassis component | interface alias |
| 2 | interface alias | port component |
| 3 | port component | MAC address, PORT_ID_MAC_ADDRESS |
| 4 | MAC address, CHASSIS_ID_MAC_ADDRESS | network address, PORT_ID_NETWORK_ADDRESS |
| 5 | network address, CHASSIS_ID_NETWORK_ADDRESS | interface name |
| 6 | interface name | agent circuit ID |
| 7 | locally assigned | locally assigned |
as_text(), as_mac() and as_network_address() read the bytes and do not look at the subtype: as_mac() turns any six-byte ID into a MacAddress, as_network_address() reads an IANA address family (1 for IPv4, 2 for IPv6) followed by an address of the right size. Match on subtype first. In the corpus, the 205 LLDPDUs of the PROFINET captures carry locally assigned IDs, the 71 Cisco ones a MAC chassis ID and an interface name.
Capabilities, management addresses, organizations
system_capabilities() returns SystemCapabilities { capabilities, enabled }, two bit fields of what the device can do and of what is on. A constant names each bit, OTHER (0x0001), REPEATER, BRIDGE (0x0004), WLAN_ACCESS_POINT, ROUTER (0x0010), TELEPHONE, DOCSIS_CABLE_DEVICE, STATION_ONLY (0x0080), C_VLAN_COMPONENT, S_VLAN_COMPONENT and TWO_PORT_MAC_RELAY (0x0400), and is_enabled(bit) reads enabled.
#![allow(unused)] fn main() { pub struct ManagementAddress<'a> { pub address_subtype: u8, // IANA address family: 1 IPv4, 2 IPv6, 6 MAC... pub address: &'a [u8], pub interface_subtype: u8, // interface numbering: 1 unknown, 2 ifIndex, 3 system port pub interface_number: u32, pub oid: &'a [u8], // the SNMP object that describes the address, often empty } }
The value of a Management Address TLV is the length of the address string (2 to 32 bytes, its subtype included), the subtype and the address, the interface numbering subtype, the interface number on four bytes, the length of the OID and the OID, at most 128 bytes. These lengths must tile the value exactly, or the whole LLDPDU is refused with InvalidManagementAddress. management_addresses() yields the addresses in wire order, and ip() gives the IpAddr of an IPv4 or IPv6 one.
#![allow(unused)] fn main() { pub struct OrganizationTlv<'a> { pub oui: [u8; 3], pub subtype: u8, pub info: &'a [u8], } }
organization_tlvs() yields the TLVs of type 127 in wire order, and organization() names six OUIs: 00-80-C2 IEEE 802.1, 00-12-0F IEEE 802.3, 00-0E-CF PROFINET, 00-12-BB LLDP-MED, 00-80-63 Hirschmann and 00-01-42 Cisco; any other is None. info stays raw.
Frame 2165 of The-Ultimate-PCAP.pcapng, a Cisco C2960, then the same frame cut in the middle of its System Description (tested):
#![allow(unused)] fn main() { #[test] fn lldp_ids_management_addresses_and_a_cut_lldpdu() { // Frame 2165 of The-Ultimate-PCAP.pcapng: a Cisco C2960. let raw = hex::decode(LLDP_CISCO_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let internet = flow.internet.as_ref().unwrap(); let Some(InternetDetails::Lldp(lldp)) = &internet.details else { panic!("expected a decoded LLDPDU in details"); }; // The subtype says how to read an ID; the accessors do not check it. assert_eq!(lldp.chassis_id.subtype, CHASSIS_ID_MAC_ADDRESS); assert_eq!( lldp.chassis_id.as_mac(), Some(MacAddress([0x00, 0x21, 0x1b, 0xae, 0x31, 0x80])) ); assert_eq!((lldp.port_id.subtype, lldp.port_id.as_text()), (5, Some("Gi0/1"))); assert_eq!(lldp.time_to_live, 120); assert_eq!(lldp.system_name(), Some("CCNP-LAB-S1.webernetz.net")); assert_eq!(lldp.port_description(), Some("GigabitEthernet0/1")); assert_eq!(lldp.tlv(6).map(|tlv| tlv.value.len()), Some(243)); // System Description let ips: Vec<IpAddr> = lldp.management_addresses().filter_map(|a| a.ip()).collect(); assert_eq!( ips, [ "192.168.121.10".parse::<IpAddr>().unwrap(), "2003:51:6012:121::10".parse().unwrap() ] ); let capabilities = lldp.system_capabilities().unwrap(); assert!(capabilities.is_enabled(SystemCapabilities::BRIDGE)); assert!(!capabilities.is_enabled(SystemCapabilities::ROUTER)); // Without the EtherType, the probing Internet::try_from finds it too. let probed = Internet::try_from(flow.data_link.network_payload()).unwrap(); assert_eq!(probed.protocol_name, "LLDP"); // Cut in the middle of the System Description: the EtherType // announced LLDP, so the internet layer is corrupted. let flow = parse(LinkType::ETHERNET, &raw[..100]).unwrap(); assert!(flow.internet.is_none()); let corrupted = flow.corrupted.unwrap(); assert_eq!(corrupted.layer, CorruptedLayerKind::Internet); assert_eq!( corrupted.error.to_string(), "LLDP error: LLDP TLV type 6 at offset 48 declares 243 bytes, 36 remain" ); } }
Validations
All of them are LldpParseError, in packet_parser::errors::internet::lldp:
| Error | When |
|---|---|
TruncatedTlvHeader { offset } | a TLV header starts at offset and the frame ends before its second byte |
TlvOverflow { tlv_type, offset, declared, available } | a TLV declares more bytes than remain |
MissingMandatoryTlv { position, expected, found } | TLV number position (0 to 2) is not Chassis ID, Port ID and Time To Live in that order; found is None when the LLDPDU ends first, an empty one included |
InvalidTlvLength { tlv_type, length } | a length outside the bounds of the table above |
InvalidManagementAddress | the inner lengths of a Management Address do not tile its value |
The blind probe
Internet::try_from, the probing parser for callers without an EtherType, tries LLDP last, after GOOSE (see the internet page), and asks for more than the decoder: the last TLV must be End of LLDPDU, and the padding zeros only. The golden test runs it on the 276 LLDPDUs of the corpus, and recognizes each of them.
Oracle: 276 frames, TLV by TLV
The golden test tests/lldp_golden.rs compares every LLDP frame of three captures with tshark 4.6.6, frozen in tests/data/lldp_tshark_oracle.tsv by tools/lldp_oracle.sh (run with an empty Wireshark profile): the types and lengths of the TLVs, the chassis, the port, the TTL, the system name, the port description, the capabilities, the management addresses and the organization OUIs. The system descriptions are compared by their length only, since tshark escapes their line breaks. Each of the 276 frames is an internet layer LLDP, without corruption, with the values of tshark, and no other frame of the three captures decodes as LLDP. A second test checks the blind probe and that an LLDPDU cut by one byte before its padding is refused. The fuzz target parse_lldp runs nightly on the decoder, seeded with the SCALANCE frame and the Cisco one, without its descriptions.
| Capture | LLDP frames | Devices |
|---|---|---|
protocols/profinet/cisagov_profinet_io_cm_mixed_1.pcap | 201 | a Siemens SCALANCE X208 (siemens-x208-switch, 134 frames) and versamax-pns11 (67), PROFINET and IEEE 802.3 TLVs |
protocols/profinet/miguelob_pn.pcapng | 4 | two Siemens devices, SIMATIC NET and SIMATIC S7 in their port descriptions |
The-Ultimate-PCAP.pcapng, read in place | 71 | two Cisco switches: 12 Ethernet frames with an IPv4 and an IPv6 management address, 59 IEEE 802.3br mPackets |
The first two belong to the PROFINET corpus; the third is the Ultimate PCAP of Johannes Weber, at the root of pcaps_exemple/.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- Organization TLVs are identified, OUI and subtype, not decoded:
infostays raw, for PROFINET, IEEE 802.1, IEEE 802.3 and LLDP-MED alike. - Management addresses other than IPv4 and IPv6 are only
address_subtypeandaddress; the OID is raw bytes. - No neighbour table: the crate does not age announcements by
time_to_live, nor keep what a device announced; stateless, one LLDPDU at a time. - Reserved TLV types (9 to 126) are kept, without a bound on their length and without interpretation.
Transport
The transport layer is parsed from Internet::payload, and the internet layer says what to expect through payload_protocol.
The Transport struct
#![allow(unused)] fn main() { pub struct Transport<'a> { pub protocol: TransportProtocol, pub source_port: Option<u16>, pub destination_port: Option<u16>, /// TCP and UDP: the bytes after the header, possibly empty. `None` for every other protocol. pub payload: Option<&'a [u8]>, /// Full parsed header: TcpPacket, UdpPacket, IcmpPacket, Icmpv6Packet or EspPacket. /// `None` for the other protocols, and for an unreadable ICMP or ESP packet. pub details: Option<TransportDetails<'a>>, } }
Transport and TransportDetails are both #[non_exhaustive]; TransportDetails has Tcp, Udp, Icmp, Icmpv6 and, since 11.6.0, Esp. The identity of the layer is protocol plus the two ports: PartialEq, Hash and serialization ignore payload and details, and protocol is serialized under the key protocol_transport as its Display name ("TCP", "ICMPv6", "Unknown (150)"), the same string TransportOwned carries (#22).
TransportProtocol has a named variant for every protocol number IANA has assigned (0 to 147 and 253 to 255: Tcp, Udp, Icmp, Ipv6Icmp, Gre, Sctp, Ospfigp...) and Unknown(u8) for the unassigned range 148 to 252, so a packet carrying a protocol without a dedicated parser still gets a correct protocol label. Only TCP, UDP, ICMPv4, ICMPv6 and, since 11.6.0, ESP are decoded further.
Dispatch on the IP protocol number
#![allow(unused)] fn main() { pub fn try_from_parts(payload_protocol: Option<TransportProtocol>, payload: &'a [u8]) -> Result<Self, TransportError> { match payload_protocol { Some(TransportProtocol::Tcp) => { let tcp = TcpPacket::try_from(payload)?; /* ports, payload, details */ } Some(TransportProtocol::Udp) => { let udp = UdpPacket::try_from(payload)?; /* ... */ } Some(TransportProtocol::Icmp) => Ok(Transport { /* no ports, payload: None, details: IcmpPacket::try_from(payload).ok().map(TransportDetails::Icmp) */ }), Some(TransportProtocol::Ipv6Icmp) => Ok(Transport { /* same with Icmpv6Packet */ }), Some(TransportProtocol::Esp) => Ok(Transport { /* no ports, payload: None, details: EspPacket::try_from(payload).ok().map(TransportDetails::Esp) */ }), Some(other) => Ok(Transport { protocol: other, source_port: None, destination_port: None, payload: None, details: None }), None => Err(TransportError::UnsupportedProtocol), } } }
Same philosophy as the internet layer: the protocol number decides, there is no probing. Transport has no TryFrom<&[u8]> at all: the one that existed until 10.x guessed TCP, then UDP, blindly, and 11.0.0 removed it.
UnsupportedProtocol (which PacketFlow maps to transport: None, corrupted: None) is distinct from a TCP or UDP parse error, which reaches the caller wrapped in TransportError::TcpError or TransportError::UdpError and becomes transport: None, corrupted: Transport, with the error itself in CorruptedLayerError::Transport since 13.0.0 (its Display until 12.x). TransportError and the errors of TCP, UDP, ESP, ICMP and ICMPv6 derive Clone, PartialEq, Eq and Hash since 13.0.0. Despite its name, UnsupportedProtocol does not mean an unknown L4 protocol (those take the Some(other) arm): it means the internet layer announced nothing to parse. ARP, PROFINET, PTP over EtherType 0x88F7, GOOSE and LLDP carry no transport; an IPv4 or IPv6 fragment, the first one included, cannot be parsed safely without reassembly, which the crate does not do; an IPv6 extension chain can end in No Next Header (59). TransportError also declares PacketTooShort and InvalidTcpPacket(String), which try_from_parts never returns.
The protocols
TCP, UDP, ICMPv4, ICMPv6 and ESP are decoded further, each on its page: TCP, UDP, ICMPv4 and ICMPv6 and ESP. ESP also travels in UDP 4500 behind a NAT, where the transport layer is UDP and "ESP" is an application label; its page covers both carriers.
Checksums
TCP and UDP checksums are never verified during parsing, for the same offloading reason as IPv4 (UdpError::InvalidChecksum exists, but the parser never returns it). They need the IP pseudo-header, so the opt-in functions verify_tcp_checksum and verify_udp_checksum take the addresses:
#![allow(unused)] fn main() { use packet_parser::checksum::verify_tcp_checksum; // Some(true): present and correct; Some(false): present and wrong; // None: not verifiable (too short, UDP checksum field at 0, // or an IPv4 address mixed with an IPv6 one). let ok = verify_tcp_checksum(internet.source?, internet.destination?, internet.payload); }
ICMP and ICMPv6 checksums have no verifier: the checksum module covers the IPv4 header, TCP and UDP only.
TCP
IP protocol 6, parsed by the transport layer.
These are the 40 bytes the internet chapter handed up as payload. Unlike the IPv4 Protocol byte, nothing in a TCP header names the protocol above it: the ports, in orange, are only a hint, which the application table confirms against the content. protocol does not come from these bytes either, it is the internet layer's payload_protocol. The data offset A says the header is 10 words long, options included, so payload starts at byte 40: a SYN carries no data, and payload is Some of an empty slice.
TcpPacket holds the decoded header: TcpHeader and the payload, everything after data_offset × 4 bytes. The header exposes every field: data_offset in 32-bit words, reserved as the three raw bits, one bool per flag from ns to fin. Options are not decoded: options is the raw slice between byte 20 and the end of the header.
Structural checks (an Err means "not a readable TCP header"):
| Bytes | Field | Check | Error |
|---|---|---|---|
| 0–19 | Fixed header | the buffer holds at least 20 bytes | TcpError::PacketTooShort |
| 12, high nibble | Data offset | between 5 and 15 words, 20 to 60 bytes | TcpError::InvalidDataOffset, with the value read |
0–offset × 4 | Header and options | the buffer holds the whole header | TcpError::PacketTooShort |
Semantic checks (the header is readable, TryFrom returns Ok, and the anomaly is exposed by TcpPacket::anomaly()):
| Bytes | Field | Anomaly | Error |
|---|---|---|---|
| 13 | Flags | SYN and FIN both set | TcpError::InvalidFlags { flags }, with the whole flags byte |
| 12, bits 3 to 1 | Reserved | any of the three bits set | TcpError::ReservedBitsSet { bits } |
No conforming stack opens and closes a connection in the same segment: SYN with FIN is a classic scan and firewall-evasion signature. The reserved bits sit between the data offset and NS, and RFC 9293 §3.1 says they must be zero. NS is decoded into ns and not checked.
anomaly() names one anomaly: when both are present it returns ReservedBitsSet, which it checks first. TcpPacket::is_anomalous() gives the same verdict as a plain bool.
The pipeline keeps an anomalous transport, with its ports, and reports it in corrupted (layer: Transport, and an error that is TcpError::InvalidFlags { flags: 0x03 } and displays TCP error: Invalid TCP flags 0x03: SYN and FIN are both set). Before 11.0.0 such a segment lost its transport layer, which deprived the caller of the ports, so of any flow correlation, at the precise moment the packet is interesting (#24). Its payload stays in transport.payload but is not handed to the application probes nor to tunnel detection (application and inner are None): bytes that did not come from a conforming stack are not worth classifying. This case runs in a cold function outside the common pipeline: weaving it into the L4 and L7 stages cost about 10 ns on every TCP segment, for a case that almost never occurs.
#![allow(unused)] fn main() { if let Some(corrupted) = &flow.corrupted && corrupted.layer == CorruptedLayerKind::Transport { match &flow.transport { None => { /* structural: unreadable header */ } Some(transport) => { /* semantic: ports usable, packet suspicious */ } } // Since 13.0.0 the cause is typed: if let CorruptedLayerError::Transport(TransportError::TcpError(TcpError::InvalidFlags { .. })) = &corrupted.error { /* SYN and FIN together */ } } }
UDP
IP protocol 17, parsed by the transport layer. UDP (RFC 768) is the smallest transport header there is: two ports, a length and a checksum, eight bytes, and the datagram is the message. Most of what the crate labels above the transport layer travels in it: DNS, NTP, SNMP, DHCP, QUIC, and the tunnels.
The datagram
This is the datagram of the DNS query drawn in the packet chapter. As for TCP, the ports are in orange: they are the hint the application table starts from, never the verdict. UdpPacket keeps source_port, destination_port, length, checksum and payload, and is reached through details (TransportDetails::Udp); Transport gets its protocol from the IP header, not from these bytes.
Validations
| Bytes | Field | Check | Error |
|---|---|---|---|
| 0–7 | Header | the buffer holds at least 8 bytes | UdpError::PacketTooShort { expected, actual } |
| 4–5 | Length | equal to the number of bytes handed up | UdpError::InvalidLength { length, actual } |
payload is everything after the 8-byte header. UDP has no semantic anomaly: a datagram either parses or corrupts the layer, reported as corrupted: Transport with the error's text, for instance UDP error: UDP length field (9) doesn't match actual packet length (10).
Why an exact length
UDP is the one header whose declared length must match the buffer exactly, where IPv4 accepts a longer buffer. The reason is the layer below:
Ethernet pads short frames to 60 bytes, so a small datagram arrives with trailing zeros that are not its own. The internet layer already cuts them: it hands the transport layer data[header_len..total_length] for IPv4, 40 + payload_length bytes for IPv6, never the padding. What UDP receives is therefore exactly what IP said it carried, and a Length that disagrees with it is not a padded datagram, it is a lie about the message: a longer Length would read past the datagram into whatever follows, a shorter one would hide bytes at the end. Both are refused.
A fragmented IP datagram never reaches this parser: payload_protocol is None for it and the transport layer is skipped (IPv4 fragments), precisely because a UDP Length covers the whole datagram and the first fragment alone would fail this check while being healthy.
Above the datagram
The ports and the payload go to the application stage. Two things happen before the dispatch table:
- UDP tunnels are looked for first, by port and shape: CAPWAP on 5247, VXLAN on 4789, Geneve on 6081, GTP-U on 2152. A match makes the tunnel's name the flow's
Application::protocoland parses the carried packet intoinner(tunnels). Since 13.3.0 a CAPWAP datagram the tunnel does not peel still gets its label, from a rule of the table. - Declared ports (
ParseConfig::decode_as) are tried next, then the table's rules, those withGuard::UdporGuard::Any: a rule the RFC reserves to TCP never runs on a datagram.
An empty payload (a datagram of exactly 8 bytes) is not probed, and application stays None.
Checksum
The checksum is read into details and never verified during parsing: on a sender-side capture with hardware offloading it is uncomputed, and refusing those datagrams would reject healthy traffic. packet_parser::checksum::verify_udp_checksum(source, destination, datagram) is the opt-in check; it needs the IP addresses for the pseudo-header, and returns None rather than a verdict when the field is 0, the "not computed" value RFC 768 allows over IPv4 (over IPv6 the checksum is mandatory, and the function makes no difference: 0 is None there too).
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- UDP-Lite (IP protocol 136) is another protocol number: the flow gets
TransportProtocol::Udpliteas its name, without ports or payload. - No reassembly, as everywhere in the crate: a datagram split by IP fragmentation has no transport layer.
- The checksum is not a validation: a wrong checksum parses like a right one; see above.
ICMPv4 and ICMPv6
IP protocol 1 and IPv6 next header 58, parsed by the transport layer.
ICMP has neither ports nor sessions. It is reached through the IP protocol number (1, or next header 58 for ICMPv6), never through probing, and the two versions have separate parsers: their type numbering is disjoint (128 is an echo request in ICMPv6, 8 is undefined there).
Two deliberate choices:
payloadstaysNone: nothing stacks above ICMP, and exposing its bytes would hand them to the application probes, which would mislabel them. The decoded message is indetails(TransportDetails::Icmp/Icmpv6).- an unreadable ICMP message does not corrupt the flow: the protocol is correctly identified by the IP header, so
protocolis set and onlydetailsfalls back toNone. TheIcmpError/Icmpv6Erroris discarded; to know why, runIcmpPacket::try_fromorIcmpv6Packet::try_fromoninternet.payload.
Decoded messages, in IcmpPacket::body (IcmpBody) and Icmpv6Packet::body (Icmpv6Body), after the common message_type, code and checksum:
- Echo request/reply (ICMPv4 8/0, ICMPv6 128/129): identifier, sequence number, data.
- Error reports, which quote the datagram that caused them: ICMPv4 destination unreachable (3), redirect (5), time exceeded (11) and parameter problem (12); ICMPv6 destination unreachable (1), packet too big (2), time exceeded (3) and parameter problem (4). The four type-dependent bytes stay raw in
rest_of_header(next-hop MTU, parameter-problem pointer..., to read according to type and code), and the quoted bytes are exposed zero-copy asoriginal_datagram/invoking_packet, not parsed. - Neighbor discovery (ICMPv6 only, RFC 4861): router solicitation (133), router advertisement (134: current hop limit, M/O flags, router lifetime, reachable time, retransmit timer), neighbor solicitation (135: target address) and neighbor advertisement (136: R/S/O flags, target address), each with its NDP options as raw bytes. Redirect (137) is not interpreted.
- any other type:
Other, the raw bytes after the common header.
What makes a message unreadable:
| Check (error variant) | ICMPv4 (IcmpError) | ICMPv6 (Icmpv6Error) |
|---|---|---|
Common header: type, code, checksum (InvalidLength) | 4 bytes | 4 bytes |
Code defined for the type (InvalidCodeForType) | echo: 0; destination unreachable: 0–15; redirect: 0–3; time exceeded: 0–1; parameter problem: 0–2 | destination unreachable: 0–7; packet too big: 0; time exceeded: 0–1; parameter problem: 0–2; echo and the four ND messages: 0 |
Echo: identifier and sequence (InvalidEchoLength) | 8 bytes | 8 bytes |
Error report (InvalidErrorPayloadLength) | 8 + 28 bytes: an option-less IPv4 header and the first 8 data bytes, as RFC 792 requires | 8 + 40 bytes: the fixed IPv6 header (RFC 4443 §3) |
Neighbor solicitation/advertisement: target address (InvalidNeighborLength) | – | 24 bytes |
Router solicitation / advertisement: fixed fields (InvalidRouterLength) | – | 8 / 16 bytes |
An error report quoting less than that minimum is refused rather than exposed: routers sometimes truncate below it, and the consumer would read a partial IP header. A type the crate does not interpret has no code constraint: it parses as Other and never fails.
ESP
Encapsulating Security Payload, RFC 4303: the IPsec packet that encrypts and authenticates. Decoded since 11.6.0 (#124), with IKE and as part of the defense lot (#125). Only two fields can be read without the SA, the SPI and the sequence number; everything after them (initialization vector, data, padding, next header, ICV) depends on the algorithm IKE negotiated, and stays bytes. The module is packet_parser::parse::transport::protocols::esp, the error type EspError is in packet_parser::errors::transport::esp.
ESP travels two ways, and the crate follows both:
- natively, IP protocol 50 (IPv6 next header 50): the transport layer decodes it into
TransportDetails::Esp, like ICMP, without ports or payload; - in UDP 4500 behind a NAT (RFC 3948): the datagram gets the application label
"ESP", andEspPacket::try_fromdecodes the UDP payload.
Before 11.6.0, protocol 50 already had its name, TransportProtocol::Esp, like every number IANA assigns, and nothing else.
The packet
#![allow(unused)] fn main() { #[non_exhaustive] pub struct EspPacket<'a> { pub spi: u32, // identifies the security association, with the destination address pub sequence: u32, // anti-replay counter, increasing per association pub payload: &'a [u8], // the rest: IV, encrypted data, padding, next header, ICV } }
| Bytes | Field | Note |
|---|---|---|
| 0–3 | spi | big-endian; 0 is reserved and never sent (RFC 4303 §2.1) |
| 4–7 | sequence | big-endian |
| 8 to the end | payload | borrowed; its parts cannot be told apart without the algorithm and the key of the SA |
Two checks, both EspError: fewer than the 8 bytes of SPI and sequence number is PacketTooShort { expected, actual }, an SPI of zero is ReservedSpi. Eight bytes are enough, payload is then empty.
Native ESP: IP protocol 50
The transport dispatch has an arm for ESP, next to the ICMP ones:
#![allow(unused)] fn main() { Some(TransportProtocol::Esp) => Ok(Transport { protocol: TransportProtocol::Esp, source_port: None, destination_port: None, payload: None, details: EspPacket::try_from(payload).ok().map(TransportDetails::Esp), }), }
The consequences are those of ICMP:
payloadstaysNone: nothing readable stacks above ESP, and handing ciphertext to the application probes would only earn it false labels.applicationisNone.- An unreadable packet does not corrupt the flow: the IP header named the protocol, so
protocolisEsp,detailsfalls back toNoneandcorruptedstaysNone.EspPacket::try_from(internet.payload)gives the reason. - The SPI is not part of the identity of the transport layer, which is the protocol and the ports, both
Nonehere:PartialEq,Hashand serialization ignoredetails, andto_owned_flowdrops it. Two ESP packets of different SAs between the same hosts compare equal at the transport layer.
Over IPv6, next header 50 ends the walk of the extension headers (IPv6), and the same arm decodes the packet. Frame 5 of the corpus's site-to-site VPN, the same packet under the SPI of the VPN's other SA, then an IPv6 packet of The-Ultimate-PCAP.pcapng (tested):
#![allow(unused)] fn main() { #[test] fn native_esp_is_decoded_by_the_transport_layer() { let raw = hex::decode(NATIVE_ESP_IPV4_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let transport = flow.transport.as_ref().unwrap(); assert_eq!(transport.protocol, TransportProtocol::Esp); assert_eq!( (transport.source_port, transport.destination_port), (None, None) ); // Nothing readable stacks above: no payload, so no application probe. assert!(transport.payload.is_none()); assert!(flow.application.is_none() && flow.corrupted.is_none()); let Some(TransportDetails::Esp(esp)) = &transport.details else { panic!("expected the ESP header in details"); }; assert_eq!(esp.spi, 0x5fbd_60dc); assert_eq!(esp.sequence, 1); assert_eq!(esp.payload.len(), 112); // IV, ciphertext, trailer and ICV // The JSON names the protocol; the SPI, in details, is serialized // neither with the flow nor with its owned copy. for json in [ serde_json::to_value(&flow).unwrap(), serde_json::to_value(flow.to_owned_flow()).unwrap(), ] { assert_eq!(json["protocol_transport"], "ESP"); let text = json.to_string(); assert!(!text.contains("spi") && !text.contains(&esp.spi.to_string())); } // Nor is it compared: under the SPI of the VPN's other SA, the same // packet has other details but the same transport layer. let mut other_sa = raw.clone(); other_sa[34..38].copy_from_slice(&0xa70b_bb39_u32.to_be_bytes()); let other_flow = parse(LinkType::ETHERNET, &other_sa).unwrap(); assert!(matches!( &other_flow.transport.as_ref().unwrap().details, Some(TransportDetails::Esp(other)) if other.spi != esp.spi )); assert_eq!(other_flow.transport, flow.transport); // Over IPv6, next header 50 ends the extension walk: same layer. let raw = hex::decode(NATIVE_ESP_IPV6_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.internet.as_ref().unwrap().protocol_name, "IPv6"); let Some(TransportDetails::Esp(esp)) = &flow.transport.as_ref().unwrap().details else { panic!("expected the ESP header in details"); }; assert_eq!((esp.spi, esp.sequence), (0x3d71_3155, 1)); } }
The same frame with its SPI set to zero (tested):
#![allow(unused)] fn main() { #[test] fn an_unreadable_esp_packet_does_not_corrupt_the_flow() { let mut raw = hex::decode(NATIVE_ESP_IPV4_HEX).unwrap(); raw[34..38].copy_from_slice(&[0, 0, 0, 0]); // SPI 0, reserved by RFC 4303 let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let transport = flow.transport.as_ref().unwrap(); assert_eq!(transport.protocol, TransportProtocol::Esp); // still named assert!(transport.details.is_none()); assert!(flow.corrupted.is_none()); // The reason is one call away, on the internet payload. let internet = flow.internet.as_ref().unwrap(); assert_eq!( EspPacket::try_from(internet.payload), Err(EspError::ReservedSpi) ); } }
The corpus has 8 native ESP packets, frames 5 to 12 of ikev2_s2s_ipsec_vpn_aes_gcm.pcapng: two SAs, 0x5fbd60dc and 0xa70bbb39, sequence numbers 1 to 4 each. The-Ultimate-PCAP.pcapng has 1 593, 542 over IPv4 and 1 051 over IPv6, the counts tshark gives; a run of 11.6.0 decodes every one of them into TransportDetails::Esp.
In UDP 4500, behind a NAT
A NAT rewrites ports, and ESP has none. Behind a NAT, ESP rides in UDP 4500 (RFC 3948), sharing the port with IKE and with the keepalives that hold the NAT mapping open. The IKE page explains how UdpEncapsulation::classify tells the three apart; two rules of the table, right after the IKE rule, give the other two labels:
#![allow(unused)] fn main() { port_rule(ApplicationProtocol::Esp, Guard::Udp, is_nat_t_udp_port, ProbeId::EspNatT), // 4500 port_rule(ApplicationProtocol::NatKeepalive, Guard::Udp, is_nat_t_udp_port, ProbeId::NatKeepalive), // 4500 }
Both look at UDP 4500 only, on either side; UDP 500 carries neither.
"ESP":classifyreturnsUdpEncapsulation::Esp, at least 8 bytes that do not start with the four zero bytes of the non-ESP marker, andEspPacket::try_fromaccepts them. The flow keeps its UDP transport, and the ESP packet istransport.payload, decoded byEspPacket::try_fromwhen needed. It is a label, not a tunnel: what ESP carries is encrypted, andinnerstaysNone."NAT-keepalive": a single0xFFbyte (RFC 3948 §2.3),UdpEncapsulation::Keepalive. There is nothing to decode. The corpus ofprotocols/ipsec/has none;The-Ultimate-PCAP.pcapnghas three, frames 46989, 47000 and 47009.
Frame 11 of ipsec_isakmp_esp.pcap, then the first keepalive of the Ultimate PCAP (tested):
#![allow(unused)] fn main() { #[test] fn esp_and_keepalives_on_udp_4500() { // Frame 11: an ESP packet, non-zero SPI first. let raw = hex::decode(NAT_T_ESP_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!( flow.application.as_ref().unwrap().protocol.label(), "ESP" ); assert!(flow.inner.is_none()); // a label, not a tunnel: nothing to peel let payload = flow.transport.as_ref().unwrap().payload.unwrap(); assert_eq!( UdpEncapsulation::classify(payload), Ok(UdpEncapsulation::Esp(payload)) ); let esp = EspPacket::try_from(payload).unwrap(); assert_eq!((esp.spi, esp.sequence), (0xcbb7_a0c6, 1)); assert_eq!(esp.payload.len(), payload.len() - 8); // Frame 46989 of the Ultimate PCAP: one byte, 0xFF. let raw = hex::decode(NAT_KEEPALIVE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!( flow.application.as_ref().unwrap().protocol.label(), "NAT-keepalive" ); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); assert_eq!(payload, [0xff]); // the Ethernet trailer is cut by IPv4 assert_eq!( UdpEncapsulation::classify(payload), Ok(UdpEncapsulation::Keepalive) ); } }
ESP in UDP on another port is declared with ParseConfig::decode_as(port, DecodeAsProtocol::Esp), a variant added in 11.6.0: the same probe and the same transport guard as the rule of port 4500. The keepalive has no DecodeAsProtocol (tested):
#![allow(unused)] fn main() { #[test] fn esp_on_another_port_needs_decode_as() { let mut raw = hex::decode(NAT_T_ESP_HEX).unwrap(); move_to_port_4501(&mut raw); assert_eq!(label(&raw, &ParseConfig::new()), Some("Unknown")); let config = ParseConfig::new().decode_as(4501, DecodeAsProtocol::Esp); assert_eq!(label(&raw, &config), Some("ESP")); // A declaration names a protocol, and that protocol's probe decides. let config = ParseConfig::new().decode_as(4501, DecodeAsProtocol::Ike); assert_eq!(label(&raw, &config), Some("Unknown")); // The keepalive has no Decode As: off 4500, its byte is just a byte. let mut raw = hex::decode(NAT_KEEPALIVE_HEX).unwrap(); move_to_port_4501(&mut raw); let config = ParseConfig::new().decode_as(4501, DecodeAsProtocol::Esp); assert_eq!(label(&raw, &config), Some("Unknown")); } }
Oracle
The golden test of the IKE page, tests/ipsec_golden.rs (oracle), covers ESP too: 323 packets, SPI and sequence number compared with tshark 4.6.6, the 8 native ones and the 315 datagrams of ipsec_isakmp_esp.pcap, in UDP 4500. For a native packet it also checks that the transport has no payload and the flow no application; for a datagram, that the label is "ESP" and that classify returns Esp. In the golden histogram "ESP" went from 0 to 315, and the native packets stay without application, like ICMP. The fuzz target parse_ipsec runs EspPacket::try_from nightly: when it accepts, the SPI is not zero and payload is everything after the first 8 bytes.
The Ultimate PCAP, which the golden test does not read, adds 7 datagrams labelled "ESP" and the 3 keepalives above.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- Nothing is decrypted, and the end of the packet is not split: padding, next header and ICV cannot be told apart without the key and the algorithm of the SA, which a stateless parser does not have.
- No SA state:
sequenceis read, not checked against an anti-replay window, and no ESP SPI is linked to the IKE exchange that negotiated it. - AH (IP protocol 51) is not decoded: over IPv4 the flow gets
TransportProtocol::Ahwithout details; over IPv6, AH is one of the extension headers the internet layer walks, and what follows it is the transport protocol. - ESP over TCP is not recognized: both rules are
Guard::Udp.
Application
The application layer is where the rule "the port never decides alone" is put to the test, and where most of the design decisions of the crate were taken after real captures proved a naive approach wrong.
A classification, not a decode
#![allow(unused)] fn main() { pub struct Application { pub protocol: ApplicationProtocol, // Dns, Tls, Http, Unknown... } }
PacketFlow::application is a label. It says which protocol the transport payload looks like, not what the message contains. Since 12.0.0 the label is an enum, ApplicationProtocol, #[non_exhaustive], with one variant per label: a match on it is checked by the compiler, where 11.x compared strings (application_protocol: &'static str). It is Copy, so classification still costs no allocation. protocol.label() gives the text the crate has always written, byte for byte ("DNS", "IEC 104", "BACnet/IP"); Display and the JSON output write that text, under the key application_protocol as before, and FromStr reads it back, refusing a text that is no label (UnknownApplicationLabel). ApplicationProtocol::ALL lists the 60 labels of the crate: the 52 of the dispatch table, the six tunnels, Stp and Unknown.
Since 13.0.0 one more variant, Custom(&'static str), carries the label of a parser added by the caller. It is not in ALL, and FromStr does not build it: the text alone does not say which parser gave it. ParseConfig::application_protocol (13.1.0) reads a label back with the configuration that produced it, Custom included. A variant that carries data takes away the discriminants of the others, so a cast protocol as u8 no longer compiles. The rewrite of a 11.x match is in MIGRATION-12.md, that of a cast in MIGRATION-13.md, in the crate repository.
For the actual decode, every protocol has a module under packet_parser::parse::application::protocols (except ESP, whose EspPacket is a transport decoder, in packet_parser::parse::transport::protocols::esp), and every one of them is a TryFrom<&[u8]> with its own struct and error:
#![allow(unused)] fn main() { use packet_parser::parse::application::protocols::dns::DnsPacket; if let Some(transport) = &flow.transport && let Some(payload) = transport.payload && let Ok(dns) = DnsPacket::try_from(payload) { // counts: questions, answers, authority records, additional records println!("{} questions, {} answers", dns.header.counts[0], dns.header.counts[1]); } }
Why separate the two? Because the label is the thing every consumer needs on every packet (a flow matrix, a protocol histogram), and it must be cheap and stateless. Decoding DNS names or TLS extensions allocates and only some consumers need it.
Supported protocols
The Protocols page has one row per label: its detection route, its page, its oracle and the release it arrived in.
The dispatch table gives 52 labels: DNS (plus its mDNS and LLMNR forms), TLS, SNMP, NTP, DHCP, DHCPv6, HTTP (requests and, since 11.7.0, responses), MQTT, PostgreSQL, FTP, SMTP, NNTP, SSH (identification string only), SSDP, NetBIOS (NBNS, NBSS), OpenVPN, Modbus/TCP and UMAS (and, since 12.0.0, Modbus over UDP 502), EtherNet/IP, OPC UA, S7Comm, COTP, AMS, GIOP, SRVLOC, ASTERIX (eleven categories), QUIC, Bitcoin, PTP (IEEE 1588, on UDP 319/320), and, since 11.6.0, DNP3, IEC 60870-5-104, BACnet/IP, RADIUS, RDP, WireGuard, DIS, STANAG 5066 SIS, RTPS, IKE, and ESP inside UDP 4500 with its one-byte NAT-keepalive; since 11.8.0, Valmet DNA, the proprietary process network of Metso and Valmet distributed control systems; since 13.0.0, Java RMI; since 13.2.0, SIP; since 13.3.0, NMF, DCE/RPC, RTCP, and CAPWAP for the datagrams its tunnel does not peel. STP gets its label from the link layer (see below).
One label has a decoder and no rule: RTP, new in 13.3.0, is given on a port declared with Decode As and nowhere else. Its header has two fixed bits, too few for a rule that would not name other traffic.
Some protocols are decoded below the table and get no label: PTP straight over Ethernet (EtherType 0x88F7), GOOSE (0x88B8) and LLDP (0x88CC) are internet layers, and native ESP, IP protocol 50, is a transport layer whose SPI and sequence number are in TransportDetails::Esp, with no application payload, like ICMP.
A probed payload that matches nothing is labelled "Unknown". An empty payload (a pure ACK) is not probed at all and application stays None.
How the label is chosen: one ordered table
The words of this chapter, probe, rule, guard, blind, terminal port, are defined in the Glossary.
The first version of the crate was a cascade of if XxxPacket::try_from(payload).is_ok() { return "Xxx" }, spread over two files, with port guards applied unevenly and one override where the port beat the content. Three problems showed up on real traffic:
- false positives: NTP probed on TCP labelled TLS encrypted alerts "NTP" (
0x15is a plausible LI/VN/mode byte); a BOOTP packet looked like an SLP header; FTP/SMTP/NNTP replies are byte-for-byte identical; - double probing: the same parser ran twice on the same payload (once port-guarded, once blind);
- pathological cost: a 64 KiB GRO segment was fully parsed by every probe in the cascade.
The dispatch is now one ordered table, RULES, in src/parse/dispatch/rules.rs (src/parse/dispatch.rs until 11.8.2 split it into rules.rs, probes.rs, ports.rs and tests.rs). Each rule has:
#![allow(unused)] fn main() { struct Rule { label: ApplicationProtocol, guard: Guard, // Tcp, Udp or Any: the transports the RFC allows ports: Option<fn(Option<u16>) -> bool>, // optional port guard (either port) ports_veto: Option<fn(Option<u16>) -> bool>, // ports on which the rule must NOT fire probe: ProbeId, // the content check terminal_on_port: bool, // port reserved by RFC: the verdict is final } }
and the invariants are:
-
A rule with a port guard labels only if port and content agree. The port alone never decides.
OPC UAon port 4840 is still checked byOpcuaPacket::try_from. -
Every probe runs at most once per payload. Failures are memoized by
ProbeIdin a bitmask, one bit of au128for each of the 74 probes (au64until 12.1.0, which had 59): a rule sharing a probe with an earlier one (port-priority then blind fallback) never re-runs it. -
A probe judges the bytes its decoder will read; only the text probes stop at
PROBE_CAP(Limits). Since 11.7.0 every other probe runs on the real payload (#184, #185): most decoders want it tiled to the last byte (SNMP, Modbus/TCP, ASTERIX, DIS, RTPS...) or covered by a declared length that must fit in it (NBSS, DNS over TCP, TLS...), and a prefix proves neither. The probes of the four text protocols, FTP, SMTP, NNTP and HTTP, keep the cap,PROBE_CAP= 18 432 bytes (18 KiB). They validate their text over its whole length: in UTF-8 for FTP and SMTP, the first line in UTF-8 and the octets of what follows for NNTP, the head in UTF-8 for HTTP. The fuzz oracle of FTP, SMTP and NNTP off their ports,fuzz/oracles/text_protocols.rs, copies the cap so that it judges the same bytes as their probes. What lies beyond the cap is not seen: a text message is judged on its first 18 432 bytes alone.Before 11.7.0, 43 of the 57 probes read only that prefix, the bound that #20 put on the cost of 64 KiB GRO segments. Beyond the prefix, a probe could label what its decoder refuses, or miss a complete message:
Payload Before 11.7.0 The fault an SNMP GetResponse of 18 432 bytes followed by a hundred null bytes "SNMP"the decoder refuses it an exact DNS response of 20 041 bytes "Unknown"a complete message, missed a TLS 1.2 record of 18 437 bytes, the maximum of RFC 5246 §6.2.3 "Unknown"a complete message, missed Reading everything keeps the cost linear. A UDP payload is bounded by its datagram, and on TCP each decoder stops at its first structural error. The measures, in release:
Input Cost Source a 60 000-byte TCP segment, through parse()at most 31 µs #185 65 505 bytes of ASTERIX records 2.7 ms, 3.8 times the cost of the 18 432 bytes of the cap #184 the worst DNS case: a 255-byte name pointed at by 10 871 questions, in 65 497 bytes 39 ms #184 The bound on names is what keeps the DNS cost linear (see Tightening a blind probe). No label of the corpus moved: apart from six RTPS datagrams, already read whole, none of its 210 captures carries a payload longer than the cap.
-
The order of the table is the priority, inspectable, testable, and locked by a golden snapshot over the reference captures.
Each rule is three gates in a row, and a payload stops at the first rule whose three gates open. The TLS rule has no port guard, so its second gate always opens: the ClientHello is labelled by its content, whatever the port. A probe that fails is not re-run by a later rule that shares it. Two outcomes do not come from a rule: an empty payload is never probed (application: None), and a payload no rule matched is "Unknown", except on the terminal mDNS and LLMNR ports, where a failed probe ends the search with None (rules 14 and 15 below).
Reading the table
In 13.3.0 the table has 78 rules in two blocks: the 45 rules of the port block, then a blind cascade of 33. 12.0.0 had 65, 40 then 25. Thirteen rules came in with 13.x:
| Release | Rules | Why |
|---|---|---|
| 13.0.0 | 35 and 67, Java RMI on TCP 1099, then blind after GIOP | the new decoder (#313) |
| 13.1.0 | 3, DHCP on UDP 67 and 68 | a DHCP message whose secs equals the datagram length came out DIS, even from 68 to 67 (#294) |
| 13.1.0 | 4 and 5, SRVLOC on UDP and TCP 427 | an SLPv1 SrvTypeRqst of 20 bytes came out RADIUS on UDP 427 (#294) |
| 13.1.0 | 24, QUIC long header of any version on UDP 443 | a Version Negotiation or a reserved version came out Unknown (#299) |
| 13.1.0 | 57, EtherNet/IP on UDP | the blind EtherNet/IP rule split in two: on TCP, several complete messages may tile a segment (#288) |
| 13.1.0 | 65, SSH after other lines | a server may send lines before its banner (RFC 4253 §4.2); this rule comes after HTTP (#307) |
| 13.2.0 | 63, SIP, blind on TCP and UDP, before HTTP | the new decoder (#342) |
| 13.3.0 | 74, CAPWAP on UDP 5246 and 5247 | the datagrams the tunnel does not peel were "Unknown" (#355) |
| 13.3.0 | 75, RTCP, blind on UDP | the new decoder (#354) |
| 13.3.0 | 76, NMF, blind on TCP | the new decoder (#352) |
| 13.3.0 | 77, DCE/RPC, blind on TCP, before MQTT | the new decoder (#356) |
Every rule from DHCP on is therefore lower than in an edition of the book for 12.x: compare rules by label, not by number. The port block also holds four rules without a port guard that must come early: the blind S7Comm rule, which must beat COTP even on port 102, and the three rules that recognize FTP, SMTP and NNTP off their ports. The reverse exists since 13.3.0: the cascade holds one rule with a port guard, CAPWAP, placed after every UDP probe that has a signature so that a datagram which merely drew 5246 or 5247 as its source port keeps its own label. The source writes a rule with one of two constructors, or with the whole struct when a field differs from their defaults:
#![allow(unused)] fn main() { static RULES: &[Rule] = &[ port_rule(ApplicationProtocol::Snmp, Guard::Udp, is_snmp_udp_port, ProbeId::Snmp), port_rule(ApplicationProtocol::Dhcpv6, Guard::Udp, is_dhcpv6_udp_port, ProbeId::Dhcpv6), rule(ApplicationProtocol::S7Comm, Guard::Tcp, ProbeId::S7Comm), // ... Rule { label: ApplicationProtocol::Ftp, guard: Guard::Tcp, ports: None, ports_veto: Some(is_text_protocol_port), probe: ProbeId::FtpUnambiguous, terminal_on_port: false, }, // ... port_rule(ApplicationProtocol::Ntp, Guard::Udp, is_ntp_udp_port, ProbeId::Ntp), // --- blind cascade, with the transport guards the RFCs impose --- rule(ApplicationProtocol::Ntp, Guard::Udp, ProbeId::NtpBlind), // ... rule(ApplicationProtocol::Mqtt, Guard::Tcp, ProbeId::Mqtt), ]; }
Since 12.0.0 the label of a rule is a variant of ApplicationProtocol, where 11.x wrote the text: a rule cannot give a label the enum does not have. The tables below show the text, label().
Here is the whole table, in order. A port guard matches when either port of the segment or datagram is in its list; a veto skips the rule when either port is in the veto list. Every probe reads the whole payload, except the text probes of rules 8 to 13, 63 and 64, which read its first PROBE_CAP bytes (invariant 3).
Port rules
| # | Label | Guard | Ports | ProbeId | The probe |
|---|---|---|---|---|---|
| 1 | SNMP | Udp | 161, 162 | Snmp | SnmpPacket::try_from |
| 2 | DHCPv6 | Udp | 546, 547 | Dhcpv6 | Dhcpv6Packet::try_from |
| 3 | DHCP | Udp | 67, 68 | Dhcp | DhcpPacket::try_from |
| 4 | SRVLOC | Udp | 427 | Srvloc | SrvlocPacket::try_from |
| 5 | SRVLOC | Tcp | 427 | Srvloc | the same probe |
| 6 | S7Comm | Tcp | none | S7Comm | S7CommPacket::try_from: TPKT, COTP DT and S7 header together |
| 7 | COTP | Tcp | 102 | CotpTpkt | a COTP TPDU behind the first TPKT header (cotp_from_tpkt) |
| 8 | FTP | Tcp | 21 | Ftp | FtpMessage::try_from, first PROBE_CAP bytes |
| 9 | SMTP | Tcp | 25, 587 | Smtp | SmtpMessage::try_from, first PROBE_CAP bytes |
| 10 | NNTP | Tcp | 119 | Nntp | NntpMessage::try_from, first PROBE_CAP bytes |
| 11 | FTP | Tcp | vetoed on 21, 25, 587, 119 | FtpUnambiguous | a complete command whose verb only FTP has: RETR, STOR, PASV, APPE, RNFR, RNTO, MKD, CDUP, EPSV, EPRT, NLST; first PROBE_CAP bytes |
| 12 | SMTP | Tcp | vetoed on 21, 25, 587, 119 | SmtpUnambiguous | a complete command whose verb only SMTP has: EHLO, HELO, MAIL, RCPT; first PROBE_CAP bytes |
| 13 | NNTP | Tcp | vetoed on 21, 25, 587, 119 | NntpUnambiguous | a complete command whose verb only NNTP has: ARTICLE, XOVER, XHDR, IHAVE, LISTGROUP, NEWGROUPS, NEWNEWS; first PROBE_CAP bytes |
| 14 | mDNS | Udp | 5353, terminal | Mdns | DnsPacket::try_from_mdns |
| 15 | LLMNR | Udp | 5355, terminal | Llmnr | DnsPacket::try_from_llmnr |
| 16 | SSDP | Udp | 1900 | Ssdp | SsdpPacket::try_from |
| 17 | NBNS | Udp | 137 | Nbns | NbnsPacket::try_from |
| 18 | NBSS | Tcp | 139, 445 | Nbss | NbssPacket::try_from |
| 19 | OpenVPN | Udp | 1194 | OpenVpnUdp | OpenVpnPacket::try_from |
| 20 | OpenVPN | Tcp | 1194 | OpenVpnTcp | OpenVpnPacket::from_tcp_stream: the length-prefixed form |
| 21 | AMS | Tcp | 48898 | AmsTcp | AmsPacket::try_from_tcp: the 6-byte AMS/TCP header, then the first AMS message |
| 22 | AMS | Udp | 48899 | Ams | AmsPacket::try_from: a bare AMS header |
| 23 | QUIC | Udp | 443 | QuicShortHeader | is_plausible_short_header: the 1-RTT header is opaque by design |
| 24 | QUIC | Udp | 443 | QuicLongHeaderPort | QuicPacket::is_port_match: QUIC v1 and Version Negotiation read whole, any other version by its invariants (RFC 8999 §5.1) |
| 25 | OPC UA | Tcp | 4840, 12001 | Opcua | OpcuaPacket::try_from: the last chunk may be partial, or cut in its header |
| 26 | DNS | Tcp | 53 | DnsTcp | DnsPacket::try_from_tcp: the length-prefixed form |
| 27 | DNS | Udp | 53 | Dns | DnsPacket::try_from: the datagram form |
| 28 | PTP | Udp | 319, 320 | Ptp | PtpPacket::try_from_udp |
| 29 | DIS | Udp | 3000 | DisLenient | DisPacket::try_from_lenient |
| 30 | RADIUS | Udp | 1812, 1813, 1645, 1646, 3799 | Radius | RadiusPacket::try_from |
| 31 | BACnet/IP | Udp | 47808 to 47823 | Bacnet | BacnetPacket::try_from |
| 32 | Valmet DNA | Udp | 2517, 4516, 4517 | ValmetDna | ValmetDnaPacket::is_port_udp_match: a coherent header, with a known family at its exact size or an unknown one, or the 42-byte beacon (TimeBeacon) |
| 33 | RDP | Tcp | 3389 | Rdp | RdpPacket::try_from |
| 34 | IEC 104 | Tcp | 2404 | Iec104 | Iec104Packet::try_from |
| 35 | Java RMI | Tcp | 1099 | JavaRmi | JavaRmiPacket::try_from: any JRMP message, the one-byte ones, the DgcAck and the ProtocolAck included |
| 36 | PostgreSQL | Tcp | 5432 | PostgresqlPort | is_plausible_postgresql_payload: a decode of compatible shape |
| 37 | IKE | Udp | 500, 4500 | Ike | IkePacket::from_udp, bare or behind the non-ESP marker |
| 38 | ESP | Udp | 4500 | EspNatT | UdpEncapsulation::classify finds ESP and EspPacket::try_from accepts it |
| 39 | NAT-keepalive | Udp | 4500 | NatKeepalive | UdpEncapsulation::classify finds the one byte 0xFF |
| 40 | STANAG 5066 | Tcp | 5066 | Stanag5066 | SisPdu::try_from |
| 41 | UMAS | Tcp | 502 | Umas | UmasPacket::is_tcp_match: MBAP headers that tile the segment, each of function 0x5A with a UMAS header |
| 42 | ModbusTCP | Tcp | 502 | ModbusTcp | ModbusTcpPacket::try_from: the envelope alone |
| 43 | ModbusUDP | Udp | 502 | ModbusTcp | rule 42's probe |
| 44 | WireGuard | Udp | 51820 | WireGuardPort | WireGuardPacket::is_port_udp_match |
| 45 | NTP | Udp | 123 | Ntp | NtpPacket::try_from: the decoder alone |
Blind cascade
| # | Label | Guard | Ports | ProbeId | The probe |
|---|---|---|---|---|---|
| 46 | NTP | Udp | none | NtpBlind | NtpPacket::is_blind_udp_match |
| 47 | RTPS | Udp | none | Rtps | magic RTPS or RTPX, then RtpsPacket::try_from |
| 48 | Valmet DNA | Udp | none | ValmetDnaBlind | ValmetDnaPacket::is_blind_udp_match: one of the two known message families, at its exact size |
| 49 | ASTERIX | Udp | none | Asterix | AsterixPacket::try_from |
| 50 | DIS | Udp | none | Dis | DisPacket::try_from: the PDUs tile the datagram |
| 51 | DNP3 | Any | none | Dnp3 | Dnp3Packet::try_from |
| 52 | RADIUS | Udp | none | Radius | rule 30's probe |
| 53 | BACnet/IP | Udp | none | Bacnet | rule 31's probe |
| 54 | Bitcoin | Tcp | none | Bitcoin | BitcoinPacket::is_tcp_match: complete messages that tile the segment, all on the network of the first |
| 55 | OPC UA | Tcp | none | OpcuaBlind | OpcuaPacket::is_blind_tcp_match: chunks that tile the segment, the last one partial of at most 16 MiB |
| 56 | EtherNet/IP | Tcp | none | EthernetIpTcp | EtherNetIpPacket::is_tcp_match: complete messages that tile the segment |
| 57 | EtherNet/IP | Udp | none | EthernetIp | EtherNetIpPacket::try_from: one message, whose length covers the datagram |
| 58 | PostgreSQL | Tcp | none | Postgresql | is_likely_postgresql_payload: compatible shape and a strong proof |
| 59 | DNS | Udp | none | DnsBlind | DnsPacket::is_blind_udp_match |
| 60 | SNMP | Any | none | Snmp | rule 1's probe |
| 61 | TLS | Tcp | none | Tls | TlsPacket::try_from |
| 62 | SSH | Tcp | none | Ssh | a segment that starts with SSH-, then SshPacket::try_from |
| 63 | SIP | Any | none | Sip | may_start_sip, then SipMessage::try_from: a complete head and the five mandatory headers, first PROBE_CAP bytes |
| 64 | HTTP | Tcp | none | Http | HttpRequest::try_from or HttpResponse::try_from, first PROBE_CAP bytes |
| 65 | SSH | Tcp | none | SshAfterLines | SshPacket::try_from: the banner after other lines of text, at most 1 024 bytes of them (SSH_MAX_PRELUDE_LENGTH) |
| 66 | GIOP | Tcp | none | Giop | magic GIOP, then GiopPacket::try_from |
| 67 | Java RMI | Tcp | none | JavaRmiBlind | JavaRmiPacket::try_from and is_self_identifying: a stream header, a Call or a Return |
| 68 | DHCP | Udp | none | Dhcp | rule 3's probe |
| 69 | SRVLOC | Any | none | Srvloc | rule 4's probe |
| 70 | UMAS | Tcp | none | Umas | rule 41's probe |
| 71 | ModbusTCP | Tcp | none | ModbusTcpBlind | ModbusTcpPacket::is_blind_tcp_match |
| 72 | QUIC | Udp | none | QuicLongHeader | QuicPacket::is_blind_udp_match: a QUIC v1 long header, whose length fits in the datagram |
| 73 | WireGuard | Udp | none | WireGuardBlind | WireGuardPacket::is_blind_udp_match |
| 74 | CAPWAP | Udp | 5246, 5247 | Capwap | is_capwap_packet: a CAPWAP header of RFC 5415, or the DTLS preamble and a DTLS 1.0 or 1.2 record |
| 75 | RTCP | Udp | none | RtcpBlind | RtcpCompound::is_blind_match: packets that tile the datagram, the first a Sender or a Receiver Report, or one feedback packet alone |
| 76 | NMF | Tcp | none | NmfBlind | NmfSegment::is_blind_match: records that tile the segment, opened by a preamble or by a sized envelope in binary XML |
| 77 | DCE/RPC | Tcp | none | DceRpc | DceRpcPdu::is_blind_match: a PDU, followed by nothing or by a second PDU |
| 78 | MQTT | Tcp | none | Mqtt | MqttPacket::try_from |
Seven probes serve more than one rule. Srvloc serves three, its UDP and TCP ports and the blind rule (4, 5, 69), and ModbusTcp two, port 502 on TCP and on UDP (42, 43). Five others serve a port rule that gives them priority and a blind rule further down: Snmp (1, 60), Dhcp (3, 68), Radius (30, 52), Bacnet (31, 53) and Umas (41, 70). A failure on the port is memoized, so the blind rule does not run it again. Some probes are crate-internal: cotp_from_tpkt, is_capwap_packet, the three verb checks, is_plausible_short_header, the is_blind_*, is_port_* and is_tcp_match functions and the two PostgreSQL predicates. A consumer reaches them through parse, which is where the label is decided. In the real file most lines carry a comment that says why they are there, often with the issue, the capture frame or the RFC section behind them. That is the point of a table over a cascade: the semantics of the order are written down and cannot silently move.
Three detection routes
When choosing where a new protocol goes, the question is: can a valid payload of this protocol also be a valid payload of another protocol the crate already detect, or of arbitrary text?
| Route | When | Example |
|---|---|---|
Blind probe (rule) | the bytes identify themselves: literal marker (HTTP/, GIOP, SSH-, RTPS), CRCs (DNP3), tight binary header with plausible values (DNS, NTP), announced lengths that must cover the payload exactly (RADIUS, BACnet/IP, and PostgreSQL, which also wants a message of strong evidence), or a structure that must tile the datagram to the last byte (ASTERIX, DIS) | rule(ApplicationProtocol::Tls, Guard::Tcp, ..) |
Port-guarded (port_rule) | the signature is weak or ambiguous even with perfect checks: identical reply syntax (FTP/SMTP/NNTP), loose headers (DHCPv6, AMS, COTP, QUIC short header, PTP, IEC 104, STANAG 5066, IKE), a stack other protocols share (RDP: TPKT, COTP and MCS are also T.120's), relaxed validation (mDNS) | port_rule(ApplicationProtocol::Ftp, Guard::Tcp, is_ftp_tcp_port, ..) |
| Strong signature with transport constraint | recognizable off-port, but only defined on one transport | S7Comm: the full TPKT + COTP-DT + S7 envelope is probed on any TCP port, and the same bytes on UDP never yield the label |
Whatever the route, the transport guard is always there: the RFC says on which transport a protocol exists, and probing it elsewhere only produces false positives.
A protocol with a standard port and a signature strong enough elsewhere takes two routes at once, one rule each. With one probe, the port rule only gives it priority over the cascade: SNMP, DHCP, SRVLOC, RADIUS, BACnet/IP and UMAS. DHCP and SRVLOC got theirs in 13.1.0, when DIS and RADIUS, earlier in the cascade, took some of their messages. With two probes, the port rule keeps a lenient decoder and the blind rule a stricter one, because the standard port carries real traffic that no blind probe could prove: DNS on UDP 53 (Dns, DnsBlind, below), NTP on 123 (Ntp, NtpBlind), Modbus/TCP on 502 (ModbusTcp, ModbusTcpBlind), PostgreSQL on 5432 (PostgresqlPort, Postgresql), DIS on 3000 (DisLenient, Dis), WireGuard on 51820 (WireGuardPort, WireGuardBlind) and Valmet DNA on UDP 2517, 4516 and 4517, ports observed on a process network rather than registered (ValmetDna, ValmetDnaBlind). Since 13.x, OPC UA on 4840 and 12001 (Opcua, OpcuaBlind) and Java RMI on 1099 (JavaRmi, JavaRmiBlind) join them. NTP, Modbus/TCP and PostgreSQL have their section below.
Three protocols have more than one rule for another reason:
| Protocol | Rules | Why |
|---|---|---|
| QUIC | 23 and 24 on UDP 443, 72 on any UDP port | the opaque short header and a long header of any version only on 443; off it, the long header of QUIC v1 alone |
| SSH | 62 before HTTP, 65 after it | a segment that starts with its banner is tried first; a banner behind other lines comes after HTTP, so that an HTTP response whose body quotes a banner stays HTTP |
| EtherNet/IP | 56 on TCP, 57 on UDP | TCP may put several messages in a segment; a UDP datagram carries one |
Tightening a blind probe
A blind probe is only as good as the captures it has been confronted with. The defense corpus added in 11.4.0 showed two probes accepting traffic that was not theirs:
- SRVLOC: 829 PTPv2
Delay_Reqmessages were labelled SRVLOC. Their header has exactly the shape of an SLPv1 one (version 1, aSrvRplyfunction, a length equal to the datagram). The SLPv1 language field must now be a two-letter ASCII ISO 639 code (RFC 2165 §7); anything else isSrvlocPacketParseError::InvalidLanguageCode. - DNS: off port 53, any UDP datagram whose first twelve bytes formed a plausible empty header was DNS, among them 37 datagrams of a radar stream. The blind rule now runs its own probe,
ProbeId::DnsBlind: the sections must consume the datagram exactly and carry at least one question or record. Port 53 keeps the tolerant decoder, so the two DNS rules no longer share a probe.
In both cases the rule kept its place in the table; what changed is what the probe demands. Both corrections only removed labels: in 11.4.0 the 866 frames concerned came out as "Unknown", and the golden histogram moved on those frames and nowhere else. The 829 Delay_Req have had their own label since 11.5.0, "PTP", from the port rule of UDP 319; the 37 radar datagrams are still "Unknown".
11.6.0 did the same for two blind rules that ran a whole decoder, NTP (#164) and Modbus/TCP (#167), and split them as DNS had been split: the tolerant decoder now runs in a port rule on the standard port, where the labels of the corpus did not move, and the blind rule has a stricter probe of its own. The NTP and Modbus/TCP sections give the details.
11.7.0 came back to the DNS blind probe (#184, #196). The probe judged only the first PROBE_CAP bytes, with two consequences:
- Sections that ended exactly at byte 18 432 were enough, whatever followed. A hundred null bytes after a response still came out
"DNS", although the probe demands sections that consume the datagram exactly. - An exact response of 20 041 bytes stayed
"Unknown".
The probe now reads the whole datagram, as the NTP blind probe does (invariant 3).
Reading more needed a bound. The length of a domain name was not limited, and each name pointing to the same QNAME read it again in full, in a time quadratic in the size of the message. A forged response of 18 425 bytes, with a QNAME of 4 602 labels and 767 records pointing to it, cost 193 ms to DnsPacket::try_from, and came out "DNS".
A name is now at most 255 bytes on the wire, pointers followed (RFC 1035 §3.1). A longer one makes DnsPacket::try_from fail in a few microseconds, and its mDNS, LLMNR and TCP variants with it. The error is DnsQueryParseError::OutOfBoundParse, the one of a name that runs past the message. tshark shows such a name as <Name too long> and goes on; the crate no longer labels the message. No frame of the corpus changed. The DNS page has the rules.
ASTERIX, whose data blocks must tile the datagram, was judged on the same prefix. It has read the whole datagram since #184.
13.1.0 tightened two more probes, after a review of the decoders against their specifications (#288). Both read only the start of a TCP segment:
| Probe | Before 13.1.0 | Since 13.1.0 |
|---|---|---|
| UMAS (rules 41, 70) | the first MBAP header alone: a UMAS header followed by text came out "UMAS" on any TCP port | MBAP headers that tile the segment, each of function 0x5A with a UMAS header (#295) |
| OPC UA, blind (rule 55) | three letters of message type and one of chunk type: CLOCK 12:00:00 came out "OPC UA" | chunks that tile the segment, the last one partial of at most 16 MiB, OPCUA_BLIND_MAX_PARTIAL_SIZE (#296) |
The 181 UMAS frames and the 187 OPC UA frames of the corpus kept their labels.
Two probes went the other way, because TCP does not keep the boundaries of messages. EtherNet/IP and Bitcoin wanted the declared length to cover the whole segment: two RegisterSession, or verack then ping, in one segment came out "Unknown", even on TCP 44818. Since 13.1.0 complete messages that tile the segment are recognized, each one valid, as PostgreSQL and OPC UA already were. A last message cut by the end of the segment is still refused, as these probes are blind. The decoders did not change: TryFrom reads one message.
On its ports, OPC UA accepts the reverse case: a complete chunk followed by 1 to 7 bytes of the next one, cut by TCP in its header. Those bytes must start one of the seven message types, HEL, ACK, ERR, RHE, OPN, MSG or CLO. 13.1.0 let them in (#296); 13.1.1 checks them from the first byte, where 13.1.0 checked nothing below three bytes (#333, found by the nightly fuzz).
The reverse defect exists too, a parser refusing its own traffic, and 11.5.0 fixed one in SRVLOC (#131): the Char Encoding field of an SLPv1 header was read on one byte instead of two (RFC 2165 §7), which shifted everything after it, the XID and, in a DAAdvert, the error code, URL and scope list; the 26 SLPv1 DAAdvert of a real capture came out "Unknown". The header now has SrvlocHeaderV1::char_encoding (u16, the IANA MIBenum, 106 for UTF-8); the old single-byte encoding is deprecated, a change that on its own calls for a minor version, not a patch. 11.6.0 fixed four more, all with real frames: NTP replies refused because of the client's clock (#161), timestamps without their era (#162), reference ids and polls an implementation does send (#165), and the PostgreSQL p message of every password or SCRAM authentication (#98).
The same review fixed parsers that refused their own traffic in 13.0.0 and 13.1.0. Each fault left a valid message "Unknown", often on the protocol's own port:
| Protocol | The refused traffic | Issue |
|---|---|---|
| NBNS | the negative response to a name query (rcode 3), and the refresh with opcode 9 | #292 |
| DHCPv6 | Relay-Forward and Relay-Reply were read with the client header; their 34-byte header is now Dhcpv6Packet::relay | #289 |
| AMS | on TCP 48898 the 6-byte AMS/TCP header before each message (AmsPacket::try_from_tcp) | #290 |
| MQTT | four valid MQTT 5 forms, AUTH (type 15) among them | #291 |
| TLS | a record of version 3.0, which RFC 5246 lets a client send | #300 |
| Bitcoin | the real regtest magic, and Testnet4; two magics of no network were accepted | #301 |
| SNMP | a Counter64 of 263 or more, 9 bytes in BER | #304 |
| FTP, SMTP, NNTP | a segment cut between CR and LF | #305 |
| FTP, NNTP | standard verbs: XPWD, XMKD, XRMD, XCUP, XCWD, LPSV, ADAT, CCC, MIC, CONF, ENC, LANG, HOST; STARTTLS, CHECK, TAKETHIS | #306 |
| SSH | lines before the banner | #307 |
| COTP | a class 0 CR that announces a TPDU of 4 096 or 8 192 bytes, which a real IEC 61850 station sends | #298 |
| DHCP | hlen 0 over InfiniBand and IEEE 1394, and BOOTP with a null vend area | #303 |
| SRVLOC | an error reply stopped after its code, and SLPv1 strings in Latin-1 or UCS-2 | #302 |
| DNS | a label that is not UTF-8, and on TCP a response without a question (AXFR) | #297 |
| QUIC | Version Negotiation and reserved versions on UDP 443 | #299 |
| LLMNR | Z bits set, and the RCODE of a query, which a receiver must ignore | #288 |
QUIC also lost a field it could not read. Header protection (RFC 9001 §5.4) masks the packet number and its length in an Initial, a 0-RTT or a Handshake packet, so packet_number is always None since 13.0.0 (#293). The DNS, LLMNR and TLS changes are on their pages.
"Decode As"
Port guards mean a server on a non-standard port is invisible to a port-guarded rule. ParseConfig::decode_as(port, DecodeAsProtocol::Xxx) declares extra ports, and parse_with applies them. Declared ports are evaluated before the table, with the same three constraints: port and content, the protocol's transport guard, and failures memoized like the table's. Ports the table marks terminal (mDNS 5353, LLMNR 5355) cannot be overridden: the caller extends the guards, never replaces them.
DecodeAsProtocol is #[non_exhaustive]. It had twenty variants in 11.5.0, Ptp the last; 11.6.0 adds seven at its end, Stanag5066, Dis, Ike, Esp, Rdp, Iec104 and WireGuard, 11.8.0 one more, ValmetDna, 12.0.0 another, ModbusUdp, 13.0.0 JavaRmi, 13.2.0 Sip, and 13.3.0 Rtp, Nmf and Rtcp: 34 in all. Each variant resolves to a label, a transport guard and a probe, and a unit test of dispatch/tests.rs checks that the label and the probe are those of a rule of the table, so that the two lists cannot drift apart. Three variants run a more lenient probe than the table does, and the test checks the stricter twin instead: WireGuard, Nmf and Rtcp. For Rtp it checks the opposite, that the table has no rule with that label:
| Variant | Label | Guard | ProbeId |
|---|---|---|---|
Ftp | FTP | Tcp | Ftp |
Smtp | SMTP | Tcp | Smtp |
Nntp | NNTP | Tcp | Nntp |
Cotp | COTP | Tcp | CotpTpkt |
Dns | DNS | Tcp on TCP, Udp otherwise | DnsTcp on TCP, Dns otherwise |
Mdns | mDNS | Udp | Mdns |
Llmnr | LLMNR | Udp | Llmnr |
Ssdp | SSDP | Udp | Ssdp |
Nbns | NBNS | Udp | Nbns |
Nbss | NBSS | Tcp | Nbss |
Snmp | SNMP | Any | Snmp |
Dhcpv6 | DHCPv6 | Udp | Dhcpv6 |
OpcUa | OPC UA | Tcp | Opcua |
PostgreSql | PostgreSQL | Tcp | PostgresqlPort |
ModbusTcp | ModbusTCP | Tcp | ModbusTcp |
EthernetIp | EtherNet/IP | Tcp on TCP, Any otherwise | EthernetIpTcp on TCP, EthernetIp otherwise |
Ams | AMS | Tcp on TCP, Any otherwise | AmsTcp on TCP, Ams otherwise |
QuicShortHeader | QUIC | Udp | QuicShortHeader |
OpenVpn | OpenVPN | Tcp on TCP, Udp otherwise | OpenVpnTcp on TCP, OpenVpnUdp otherwise |
Ptp | PTP | Udp | Ptp |
Stanag5066 | STANAG 5066 | Tcp | Stanag5066 |
Dis | DIS | Udp | DisLenient |
Ike | IKE | Udp | Ike |
Esp | ESP | Udp | EspNatT |
Rdp | RDP | Tcp | Rdp |
Iec104 | IEC 104 | Tcp | Iec104 |
WireGuard | WireGuard | Udp | WireGuard |
ValmetDna | Valmet DNA | Udp | ValmetDna |
ModbusUdp | ModbusUDP | Udp | ModbusTcp |
JavaRmi | Java RMI | Tcp | JavaRmi |
Sip | SIP | Any | Sip |
Rtp | RTP | Udp | Rtp |
Nmf | NMF | Tcp | Nmf |
Rtcp | RTCP | Udp | Rtcp |
A declared port gets the probe of the protocol's standard port: the compatible shape of PostgreSQL on 5432, the lenient reading of DIS on 3000, the envelope of Modbus/TCP on 502, the AMS/TCP header of 48898 on TCP, every message family and the beacon of Valmet DNA on 2517, 4516 and 4517. WireGuard goes further than the 51820 rule: its probe, WireGuardPacket::try_from, accepts the reserved bytes whatever the message type, where the port rule wants them null in a cookie or a data message, 51820 being a port that any peer can draw at random. Nmf and Rtcp do the same with their blind rules: on a declared port the decoder alone decides, so the one-byte records of NMF and an RTCP datagram that does not open with a report are named. Rtp has no rule to be more lenient than: a declared port is its only route. Because declared ports come before the table, a declared port names the protocol of everything its probe accepts: on a port declared ModbusTcp, a UMAS frame is "ModbusTCP" (see Modbus/TCP and UMAS).
Since 12.1.0, DecodeAsProtocol::ALL is every variant, in declaration order: the list a caller shows when it lets its user bind a protocol to a port (#274). The enum and ALL are written by one macro from one list, as ApplicationProtocol and its own ALL are, so a variant cannot be missing from it. Three lists were written by hand until then, the one of the dispatch tests and those of the fuzz targets parse_packetflow and policy_dispatch; in 11.8.0 the fuzz one lacked ValmetDna. All three now read ALL (tested):
#![allow(unused)] fn main() { #[test] fn decode_as_all_is_the_list_a_caller_offers_for_a_port() { // Every variant, in declaration order: what a "Decode As" menu shows. let offered: Vec<String> = DecodeAsProtocol::ALL .iter() .map(|protocol| format!("{protocol:?}")) .collect(); assert_eq!(offered.len(), 34); assert_eq!(offered.first().map(String::as_str), Some("Ftp")); assert_eq!(offered.last().map(String::as_str), Some("Rtcp")); // The entry the user picks goes to `decode_as` as it is. let picked = DecodeAsProtocol::ALL[0]; assert_eq!(picked, DecodeAsProtocol::Ftp); let _config = ParseConfig::new().decode_as(2121, picked); } }
The nineteen labels of the table without a variant are all given by a rule without a port guard, which probes any port, except two: NAT-keepalive, which only UDP 4500 knows, and CAPWAP, which only UDP 5246 and 5247 know. For NTP, whose port rule is more tolerant than its blind probe, this means that off port 123 the strict probe is the only way to the label.
Parsers added by the caller
Since 13.0.0 the caller can add parsers for protocols the crate does not decode, in Rust or, since 13.1.0, as rules in a TOML file. They run after the table, on a TCP or UDP payload that it left "Unknown": they never take a frame from the crate. Their label is ApplicationProtocol::Custom. The Custom parsers and rules chapter describes both.
STP: the one label without a transport
A Spanning Tree BPDU has no L3, so it can never reach this table. The pipeline checks it from the link layer (802.3 length field, bridge group address, LLC 42-42-03, valid BPDU) and labels the flow "STP" when every other layer is None.
Tunnels take the label
When the transport payload is a recognized encapsulation (CAPWAP, VXLAN, Geneve, GTP-U) the outer flow's Application::protocol is the tunnel name, and the real conversation is in inner. CAPWAP also keeps its name when there is nothing to peel, through rule 74. Next chapter.
ASTERIX
ASTERIX (All Purpose STructured EUROCONTROL SuRveillance Information EXchange, EUROCONTROL-SPEC-0149) is the exchange format of air traffic surveillance data: radar plots and tracks, ADS-B reports, system tracks, service and status messages between sensors, trackers and their users. It travels in UDP datagrams, usually multicast, and it is the first protocol of the crate with neither a magic nor a port: no IANA assignment (Wireshark proposes 8600, the maintainer's radars use 8611 and 8612, the samples of Croatia Control 21111 to 22135 and 10001), and nothing in the first bytes names the protocol. What it has is structure, and the crate recognizes it by that alone: a blind probe of the dispatch table, rule(ApplicationProtocol::Asterix, Guard::Udp, ProbeId::Asterix), placed before DNS, whose datagram form is less constrained.
Eleven categories are decoded, eight of them since 11.6.0 (#119, defense lot #125). On a real surveillance network they mix in the same datagrams, radar plots next to the service messages of the same radar, system tracks next to the status of the tracker that computes them: up to 18 data blocks in one datagram of the corpus. Module: packet_parser::parse::application::protocols::asterix, with one submodule catNNN per category, uap for the tables and fields for the types several categories share.
| CAT | Content | UAP edition | FRNs (FSPEC octets) | Typed decoder |
|---|---|---|---|---|
| 001 | monoradar plots and tracks, the generation before CAT 048 | 1.4, two UAPs | 21 for plots (3), 22 for tracks (4) | cat001::TargetReport |
| 002 | monoradar service messages, the generation before CAT 034 | 1.2 | 14 (2) | cat002::ServiceMessage |
| 008 | monoradar derived weather information | 1.3 | 14 (2) | cat008::WeatherMessage |
| 021 | ADS-B target reports, editions 2.x | 2.7 | 49 (7) | cat021::TargetReport |
| 023 | CNS/ATM ground station and service status | 1.3 | 14 (2) | cat023::StatusReport |
| 034 | monoradar service messages | 1.29 | 14 (2) | cat034::ServiceMessage |
| 048 | monoradar target reports | 1.32 | 28 (4) | cat048::TargetReport |
| 062 | SDPS system tracks | 1.21 | 35 (5) | cat062::SystemTrack |
| 063 | sensor status | 1.7 | 14 (2) | cat063::SensorStatus |
| 065 | SDPS service status | 1.6 | 14 (2) | cat065::ServiceStatus |
| 247 | version number exchange | 1.3 | 7 (1) | cat247::VersionReport |
The editions are the ones tshark 4.6.6 uses by default. The tables of the eight new categories are derived from the machine-readable definitions of zoranbosnjak/asterix-specs (BSD-3) and cross-checked with tshark on the corpus. A UAP is stable from one edition to the next, apart from the number of extents of a few extended items (I021/090, I062/080), and the table keeps the latest edition, which accepts the earlier ones. uap::uap_for(category) returns the UAP of a category, uap::SUPPORTED_CATEGORIES lists the eleven.
The datagram: data blocks
A datagram is one or more data blocks back to back. Each starts with one byte of category (CAT) and two bytes of length (LEN, header included), then holds one or more records. AsterixPacket::try_from reads blocks until the payload is consumed, and the lengths must add up to the payload exactly: a block shorter than 5 bytes or longer than what is left is AsterixError::InvalidBlockLength, fewer than 3 bytes left after a block is Truncated, and a category without a UAP is UnsupportedCategory. The datagram drawn above is frame 3 of cat_034_048.pcap: a CAT 048 track report followed by the CAT 034 sector-crossing message of the same radar (SAC 25, SIC 13), 55 + 11 = 66 bytes.
#![allow(unused)] fn main() { #[non_exhaustive] pub struct AsterixPacket<'a> { pub blocks: Vec<AsterixDataBlock<'a>>, } #[non_exhaustive] pub struct AsterixDataBlock<'a> { pub category: u8, pub length: u16, pub records: Vec<AsterixRecord<'a>>, } }
The record: FSPEC, then the UAP
A record starts with its FSPEC, a run of octets in which each of the seven high bits announces one data item and the low bit, FX, announces one more FSPEC octet. Counting the octets from 0 and the seven bits of each from 1, high bit first, bit n of octet k is Field Reference Number 7k + n. Which item an FRN names, and in what format, is fixed by the UAP of the category (uap.rs), and the number of its FRNs bounds the FSPEC: 28 FRNs for CAT 048, so at most 4 FSPEC octets (the table above gives the others). An FSPEC longer than the UAP allows, or one whose FX never drops, is FspecOverflow; an FSPEC that announces no item, only FX bits or none at all, is EmptyRecord. The FRNs the specification leaves undefined are None in the table, and a bit set on one of them is UnknownFrn: FRNs 16 to 19 of the CAT 001 plots, 12 of CAT 002 and of CAT 063, 43 to 47 of CAT 021, 10 to 12 of CAT 023, 2 and 29 to 33 of CAT 062, 8 to 12 of CAT 065, 5 of CAT 247.
#![allow(unused)] fn main() { #[non_exhaustive] pub struct Uap { pub category: u8, pub items: &'static [Option<ItemSpec>], // items[frn - 1], None for a reserved FRN pub selector: Option<UapSelector>, // when the category has several UAPs } #[non_exhaustive] pub struct ItemSpec { pub id: &'static str, // "I048/010" pub format: ItemFormat, } }
Uap::item(frn) and Uap::item_by_id("I048/240") look an item up, and Uap::max_fspec_octets() is the bound above. The items are then cut in FRN order, each one a zero-copy slice:
#![allow(unused)] fn main() { #[non_exhaustive] pub struct AsterixRecord<'a> { pub category: u8, pub fspec: &'a [u8], pub items: Vec<AsterixItem<'a>>, } #[non_exhaustive] pub struct AsterixItem<'a> { pub frn: u8, pub id: &'static str, // "I048/240"; "I048/SP", "I048/RE", "I001/RFS" pub data: &'a [u8], } }
record.item("I048/240") returns the bytes of an item, record.has(..) says whether it is there, and record.uap() returns the UAP that cut the record. A record ends where its last item ends, and the next record starts right there, until the block is consumed: the record of the drawing is the whole 52-byte body of its block.
CAT 001: two UAPs, chosen by the record
CAT 001 has one UAP for plots and one for tracks. They agree on FRNs 1 and 2 and part from FRN 3: I001/040 for a plot, I001/161 for a track. uap::CAT001, the UAP uap_for(1) returns, is the plot one, and the only UAP of the crate with a selector:
#![allow(unused)] fn main() { #[non_exhaustive] pub enum UapSelector { Cat001TargetType, // TYP, bit 8 of the first octet of I001/020: 0 plot, 1 track } }
The selector reads TYP in I001/020 (FRN 2), right after the FSPEC, or after the two bytes of I001/010 when FRN 1 is set. TYP = 1 selects uap::CAT001_TRACK, whose selector is None; without I001/020 the record is a plot, as for tshark. The bound on the FSPEC follows the UAP chosen, 3 octets for a plot and 4 for a track, and record.uap() tells which one cut the record (tested):
#![allow(unused)] fn main() { #[test] fn a_cat001_record_picks_its_uap_from_its_own_bytes() { // Frame 772 of wireshark_8579_radardata.pcap: CAT 001, 002 and 001 // blocks in one datagram. let raw = hex::decode(RADARDATA_FRAME_772_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "ASTERIX"); let packet = AsterixPacket::try_from(flow.transport.as_ref().unwrap().payload.unwrap()).unwrap(); let categories: Vec<u8> = packet.blocks.iter().map(|block| block.category).collect(); assert_eq!(categories, [1, 2, 1]); // TYP = 0 in I001/020: a plot, cut with the plot UAP, the one whose // selector would have switched to the track UAP. let plot = &packet.blocks[0].records[0]; assert_eq!(plot.uap(), Some(&uap::CAT001)); assert_eq!(uap::CAT001.selector, Some(UapSelector::Cat001TargetType)); let report = cat001::TargetReport::from_record(plot).unwrap(); let descriptor = report.descriptor.unwrap(); assert!(!descriptor.track); assert_eq!(descriptor.detection, cat001::RadarDetection::Combined); let position = report.polar_position.unwrap(); // LSB 1/128 NM in CAT 001 assert_eq!((position.range_nm(), position.azimuth_deg()), (57.25, 239.150_390_625)); assert_eq!(report.mode_3a.unwrap().to_string(), "0304"); assert_eq!(report.flight_level.unwrap().flight_level(), 350.0); assert_eq!(report.truncated_time_of_day_seconds(), Some(440.484_375)); assert!(!report.mode_2.unwrap().validated); // military IFF, not validated assert!(report.track_number.is_none()); // a track item // The CAT 002 block in between: the north marker of the same radar. let marker = cat002::ServiceMessage::from_record(&packet.blocks[1].records[0]).unwrap(); assert_eq!(marker.message_type, Some(cat002::MessageType::NorthMarker)); assert_eq!(marker.antenna_rotation_period_seconds(), Some(9.304_687_5)); let counts: Vec<(u8, u16)> = marker .plot_counts .iter() .map(|count| (count.identification, count.counter)) .collect(); assert_eq!(counts, [(1, 29), (2, 19), (3, 35)]); // primary, SSR, combined // The last block: a simulated test target, I001/020 in two extents. let test_target = &packet.blocks[2].records[0]; assert_eq!(test_target.item("I001/020"), Some(&[0x51, 0x80][..])); assert_eq!(uap::CAT001.item(2).unwrap().format, ItemFormat::Extended(&[1, 1])); } }
The corpus has no CAT 001 track: all its CAT 001 records are plots, and the track UAP is covered by the crate's unit tests, on synthetic bytes.
Eight item formats
The UAP names the format, and the format says where the item ends. The crate cuts along these rules and nothing else: at this level an item is bytes, not a value.
#![allow(unused)] fn main() { #[non_exhaustive] pub enum ItemFormat { Fixed(usize), Variable, Repetitive(usize), Compound(&'static [Subfield]), Explicit, Extended(&'static [usize]), RepetitiveFx(usize), Rfs, } }
The drawing shows five of them on real bytes:
- Fixed(n): n bytes, from the UAP.
- Variable: one-byte extents chained by their FX bit, like the FSPEC, as many as the record sets:
I048/030,I001/130,I002/050. EveryI002/050of the corpus takes two octets,0b 02in frame 30453 ofwireshark_8579_radardata.pcap, where tshark 4.6.6 stops after one (see the oracle). - Extended(extents): the bounded form, the
extendeditems of the specification. Each extent has a known size and ends with its FX bit, and the FX of the last defined extent must be 0: a record that sets it announces more than the UAP describes,ExtentOverflow.I048/020has six extents of one byte: one octet in the drawing of the record (a0, FX 0), two in the 39 short datagrams of the anonymized capture (01 60, frame 5 for one).I062/080has seven,I023/101a first extent of two bytes then one of one,I008/100a single extent of three. The extended items of CAT 021 and 048 (I021/040,I021/090,I021/271,I048/020,I048/170, and the TIS subfield ofI021/110) were unboundedVariableitems before 11.6.0, and the drawings of this page, drawn before 11.6.0, still labelI048/020andI048/170that way; the bytes and the lengths they show are unchanged. - Repetitive(n): a one-byte count
REP, thenREP × nbytes.I048/250carries the Mode S BDS registers, 8 bytes each. - RepetitiveFx(n): units of n bytes, the FX bit ending the last byte of each unit, as many as the record sets:
I062/510, three bytes per unit.Variableis the case n = 1. - Compound: a primary subfield, itself FX-chained, whose bits say which subfields follow. Each subfield is a
Subfield:Fixed,Variable,Repetitive,ExtendedorRepetitiveFx, and a bit set on aSubfield::Spare, or beyond the list, isUnknownSubfield.I048/130here announces its first three subfields, one byte each; in frame 1 of the anonymized capture the same item is a single00, a compound with no subfield at all, as in 50 of its 203 records (the other 153 carry08 df, the PAM subfield alone).record.subfield("I048/130", 1)returns the bytes of a subfield by its number in the specification, from 1, andNonewhen the item is absent, not compound, or without that subfield. - Explicit: the first byte is the length, itself included; zero is
InvalidExplicitLength. TheREandSPitems of every category are explicit, which is how a record can carry data the UAP does not describe. - Rfs: Random Field Sequencing, next section.
An item that needs more bytes than its block holds is TruncatedItem, with the item's id in the error.
Random Field Sequencing
CAT 001, 002 and 008 reserve an FRN, 21 in both UAPs of CAT 001 and 14 in CAT 002 and 008, for a Random Field Sequencing field (Part 1, edition 1.0 of 1997, §4.3.5.3; the current edition 3.1 no longer describes it): one byte N, then N data items, each introduced by its own FRN on one byte, in any order. The crate cuts the field as one item, I001/RFS, I002/RFS or I008/RFS, whose bytes start with N, and checks the items it carries against the same UAP: N = 0 is EmptyRfs; an FRN that names no item, or the RFS itself, is InvalidRfsFrn; an item the FSPEC already announces, or that the field carries twice, is DuplicateRfsFrn, since a record carries each data item once. record.rfs_items() returns the items of the field in wire order, each with its FRN and id, and record.item(id) looks through the field: an item is found wherever the record put it. No capture of the corpus carries an RFS field. The crate's unit tests cover it on synthetic bytes, and the fuzz target checks that every RFS item it decodes is the one record.item returns.
Typed values, on demand
The cut is the contract; the decoding is separate, per category, and only runs when asked for. Each catNNN module has a type whose from_record turns the usual items of a record into typed fields, every one an Option, or a Vec for the entries of I002/070 and I247/550, and returns None for a record of another category:
| Decoder | Items it reads |
|---|---|
cat001::TargetReport | 010, 020 (TargetReportDescriptor: plot or track, simulated, RadarDetection...), 040, 070, 090, 141 (truncated time of day), 050 (Mode 2); for a track, 161, 042, 200 and 170 |
cat002::ServiceMessage | 010, 000 (MessageType), 020 (sector), 030, 041 (antenna rotation period), 070 (PlotCounts), 090 (collimation error), 100 (dynamic window) |
cat008::WeatherMessage | 010, 000, 020 (vector qualifier), the vector counts of 034, 036 and 038, 040 (contour identifier), 050 (number of contour points), 090, 100 (processing status), 110, 120 |
cat021::TargetReport | 010, 040, 161, 015, 071, 130, 131, 080, 073, 075, 077, 140, 210, 070, 145, 160, 170, 020, 132 |
cat023::StatusReport | 010, 000 (ReportType), 015 (service type and identification), 070, 100 (ground station status), 101 (service configuration), 200 (operational range), 110 (service status), 120 (number of statistics) |
cat034::ServiceMessage | 010, 000 (MessageType), 030, 020 (sector), 041 |
cat048::TargetReport | 010, 140, 020, 040, 070, 090, 220, 240, 161, 042, 200, 170, 110, 250 (number of BDS registers), and since 11.6.0 050 and 055, the military IFF Mode 2 and Mode 1 codes |
cat062::SystemTrack | 010, 015, 070, 105 (WGS-84), 100, 185, 210, 060, 245, the ADR, ID and MHG subfields of 380, 040, 080, 200, 136, 130, 135, 220, 120 (Mode 2), and the sensor, position, Mode C and Mode 3/A of the last measurement, 340 |
cat063::SensorStatus | 010, 015, 030, 050 (the sensor), 060 (connection and NOGO per technology), 070 (time stamping bias), 080, 081, 090, 091, 092 (range gains and biases, azimuth and elevation biases) |
cat065::ServiceStatus | 010, 000 (MessageType), 015, 030, 020 (batch number), 040 (SDPS configuration and status), 050 |
cat247::VersionReport | 010, 015, 140, 550 (a CategoryVersion per category announced) |
The values keep what the wire carries and give their conversion beside it, never in its place: TimeOfDay::seconds() (LSB 1/128 s), FlightLevel::flight_level() (LSB 1/4 FL), range_nm() and azimuth_deg() on the polar positions (LSB 1/256 NM in CAT 048, 1/128 NM in CAT 001), latitude_deg() and longitude_deg() on the WGS-84 positions. Mode3ACode, and since 11.6.0 Mode2Code and Mode1Code, display in octal, AircraftAddress in hexadecimal, AircraftIdentification from its 6-bit ICAO characters (a code outside the alphabet is rendered ?). On the datagram drawn above, the CAT 048 record and the CAT 034 one (tested):
#![allow(unused)] fn main() { #[test] fn typed_values_are_decoded_on_demand() { // Frame 3 of cat_034_048.pcap: a CAT 048 block, then a CAT 034 block. let raw = hex::decode(CAT_034_048_FRAME_3_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "ASTERIX"); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = AsterixPacket::try_from(payload).unwrap(); let shape: Vec<(u8, u16, usize)> = packet .blocks .iter() .map(|block| (block.category, block.length, block.records.len())) .collect(); assert_eq!(shape, [(48, 55, 1), (34, 11, 1)]); let record = &packet.blocks[0].records[0]; let report = cat048::TargetReport::from_record(record).expect("a CAT 048 record"); let position = report.polar_position.unwrap(); let velocity = report.polar_velocity.unwrap(); let line = format!( "{} ({}) at {:.2} NM / {:.2}°, FL {}, {:.0} kt heading {:.1}°", report.aircraft_identification.unwrap().trimmed(), report.aircraft_address.unwrap(), position.range_nm(), position.azimuth_deg(), report.flight_level.unwrap().flight_level(), velocity.ground_speed_kt(), velocity.heading_deg() ); assert_eq!(line, "THY9TX (4BAACD) at 194.82 NM / 128.76°, FL 360, 457 kt heading 263.6°"); // Each decoder reads its own category only. assert!(cat034::ServiceMessage::from_record(record).is_none()); let service = cat034::ServiceMessage::from_record(&packet.blocks[1].records[0]).unwrap(); assert_eq!(service.message_type, Some(cat034::MessageType::SectorCrossing)); assert_eq!(service.sector_azimuth_deg(), Some(135.0)); // I048/020 is extended: one octet here (a0, FX = 0), six at most. assert_eq!(record.item("I048/020"), Some(&[0xa0][..])); let spec = record.uap().unwrap().item_by_id("I048/020").unwrap(); assert_eq!(spec.format, ItemFormat::Extended(&[1, 1, 1, 1, 1, 1])); } }
A system track of CAT 062 and the end of batch that follows it in the same datagram (tested):
#![allow(unused)] fn main() { #[test] fn a_system_track_and_the_subfields_its_decoder_skips() { // Frame 1 of cat_062_065.pcap: two CAT 062 tracks, then a CAT 065 // end of batch. let raw = hex::decode(CAT_062_065_FRAME_1_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "ASTERIX"); let packet = AsterixPacket::try_from(flow.transport.as_ref().unwrap().payload.unwrap()).unwrap(); let shape: Vec<(u8, usize)> = packet .blocks .iter() .map(|block| (block.category, block.records.len())) .collect(); assert_eq!(shape, [(62, 2), (65, 1)]); let record = &packet.blocks[0].records[0]; let track = cat062::SystemTrack::from_record(record).unwrap(); assert_eq!(track.track_number, Some(4713)); assert_eq!(track.aircraft_identification.unwrap().trimmed(), "RYR174C"); // I062/380 ID assert_eq!(track.aircraft_address.unwrap().to_string(), "4CA7A8"); // I062/380 ADR let position = track.wgs84_position.unwrap(); assert_eq!( (position.latitude_deg(), position.longitude_deg()), (41.167_123_317_718_506, 15.708_866_715_431_213) ); assert_eq!(track.barometric_altitude.unwrap().flight_level(), 390.0); let measured = track.measured_information.unwrap(); // I062/340, the last sensor assert_eq!(measured.sensor.map(|sensor| (sensor.sac, sensor.sic)), Some((25, 12))); assert_eq!(measured.range_nm(), Some(147.726_562_5)); // I062/080 is extended: four of its seven extents here. assert_eq!(record.item("I062/080"), Some(&[0x19, 0x03, 0x01, 0x08][..])); // A compound item, by subfield number: PSR age, 23 x 1/4 s; no TRK age. assert_eq!(record.subfield("I062/290", 2), Some(&[0x17][..])); assert_eq!(record.subfield("I062/290", 1), None); let end = cat065::ServiceStatus::from_record(&packet.blocks[1].records[0]).unwrap(); assert_eq!(end.message_type, Some(cat065::MessageType::EndOfBatch)); assert_eq!(end.batch_number, Some(1)); } }
And the status categories: an ADS-B ground station (CAT 023) and the editions it announces (CAT 247), a sensor seen by the tracker (CAT 063), the start of a weather picture (CAT 008) (tested):
#![allow(unused)] fn main() { #[test] fn status_of_a_ground_station_a_sensor_and_a_weather_picture() { /// The UDP payload of an Ethernet frame the pipeline labels ASTERIX. fn datagram(raw: &[u8]) -> &[u8] { let flow = parse(LinkType::ETHERNET, raw).unwrap(); assert_eq!(flow.application.unwrap().protocol.label(), "ASTERIX"); flow.transport.unwrap().payload.unwrap() } // Frame 1 of wireshark_9953_cat021023.pcap: CAT 023, an ADS-B service. let raw = hex::decode(CAT021023_FRAME_1_HEX).unwrap(); let packet = AsterixPacket::try_from(datagram(&raw)).unwrap(); let report = cat023::StatusReport::from_record(&packet.blocks[0].records[0]).unwrap(); assert_eq!(report.report_type, Some(cat023::ReportType::ServiceStatus)); let service_type = report.service.map(|service| service.service_type); assert_eq!(service_type, Some(2)); // ADS-B Ext Squitter assert_eq!(report.service_status, Some(4)); // normal assert_eq!(report.operational_range_nm, Some(255)); // Frame 428 of the same stream: CAT 247, the editions it sends. let raw = hex::decode(CAT021023_FRAME_428_HEX).unwrap(); let packet = AsterixPacket::try_from(datagram(&raw)).unwrap(); let versions = cat247::VersionReport::from_record(&packet.blocks[0].records[0]).unwrap(); let editions: Vec<(u8, u8, u8)> = versions .category_versions .iter() .map(|version| (version.category, version.main_version, version.sub_version)) .collect(); assert_eq!(editions, [(21, 0, 26), (23, 1, 20)]); // Frame 1105 of wireshark_8579_radardata.pcap: CAT 063, a sensor // operational but NOGO on every technology. let raw = hex::decode(RADARDATA_FRAME_1105_HEX).unwrap(); let packet = AsterixPacket::try_from(datagram(&raw)).unwrap(); let status = cat063::SensorStatus::from_record(&packet.blocks[0].records[0]).unwrap(); assert_eq!(status.sensor.map(|sensor| (sensor.sac, sensor.sic)), Some((34, 26))); let configuration = status.configuration.unwrap(); assert_eq!(configuration.connection, cat063::ConnectionStatus::Operational); assert!(configuration.psr_nogo && configuration.ssr_nogo && configuration.mode_s_nogo); assert!(configuration.ads_nogo && configuration.mlt_nogo); assert_eq!(status.time_stamping_bias_ms, Some(75)); // Frame 1 of wireshark_9239_cat008only-2.pcap: CAT 008, the start of // a weather picture. let raw = hex::decode(CAT008ONLY_2_FRAME_1_HEX).unwrap(); let packet = AsterixPacket::try_from(datagram(&raw)).unwrap(); let weather = cat008::WeatherMessage::from_record(&packet.blocks[0].records[0]).unwrap(); assert_eq!(weather.message_type, Some(cat008::MessageType::StartOfPicture)); assert_eq!(weather.processing_status.map(|status| status.scaling_factor), Some(6)); } }
What a typed decoder does not read stays reachable through record.item(..), and record.subfield(..) for a compound item: the BDS registers of I048/250, the subfields of I048/130 or I062/290, the vectors of a CAT 008 picture, the RE of a CAT 021 report.
The probe: all or nothing
ProbeId::Asterix is AsterixPacket::try_from(payload).is_ok(): the label is given only when the whole datagram cuts cleanly, every block of a decoded category, every record filling its block to the last byte. CAT + LEN alone would match far too many datagrams; the structure of a block of an unknown category cannot be checked, so one such block refuses the whole datagram rather than labelling half of it.
The drawing of the datagram shows three refusals. The CAT 034 block relabelled CAT 062 is still refused, but since 11.6.0 by the CAT 062 UAP, which reads its FSPEC f0 and finds FRN 2 reserved (UnknownFrn), not as the UnsupportedCategory(62) the drawing still shows; relabelled CAT 010, a category without a UAP, it is UnsupportedCategory. A length one byte too long makes the extra byte open a record whose first item is truncated; one trailing byte is Truncated, 3 bytes needed. Zero padding inside a block fails the same way: a record of 00 is EmptyRecord. A refused datagram goes on to the next rules of the table and usually comes out "Unknown", with nothing in corrupted. All five, on the bytes of the drawing (tested):
#![allow(unused)] fn main() { #[test] fn one_failure_anywhere_and_the_datagram_is_not_asterix() { // The 66-byte payload of frame 3 of cat_034_048.pcap, after Ethernet, // IPv4 and UDP; its second block, CAT 034, starts at byte 55. let raw = hex::decode(CAT_034_048_FRAME_3_HEX).unwrap(); let datagram = &raw[14 + 20 + 8..]; assert!(AsterixPacket::try_from(datagram).is_ok()); let second = 55; // Relabelled CAT 062, a decoded category: its UAP reads the FSPEC f0, // and FRN 2 is reserved in CAT 062. let mut relabelled = datagram.to_vec(); relabelled[second] = 62; assert_eq!( AsterixPacket::try_from(relabelled.as_slice()), Err(AsterixError::UnknownFrn { category: 62, frn: 2 }) ); // Relabelled CAT 010, which has no UAP in the crate. relabelled[second] = 10; assert_eq!( AsterixPacket::try_from(relabelled.as_slice()), Err(AsterixError::UnsupportedCategory(10)) ); // LEN 56 for the first block: the extra byte opens a record. let mut longer = datagram.to_vec(); longer[2] = 56; assert_eq!( AsterixPacket::try_from(longer.as_slice()), Err(AsterixError::TruncatedItem { item: "I048/020", needed: 1, actual: 0 }) ); // One trailing byte cannot hold a block header. let mut trailing = datagram.to_vec(); trailing.push(0); assert_eq!( AsterixPacket::try_from(trailing.as_slice()), Err(AsterixError::Truncated { needed: 3, actual: 1 }) ); // Zero padding inside a block: a record of 00 announces no item. let mut padded = datagram.to_vec(); padded[second + 2] += 1; padded.push(0); assert_eq!( AsterixPacket::try_from(padded.as_slice()), Err(AsterixError::EmptyRecord { category: 34 }) ); // In the frame, the refused datagram goes on to the next rules. let mut frame = raw.clone(); frame[14 + 20 + 8 + second] = 10; let flow = parse(LinkType::ETHERNET, &frame).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "Unknown"); assert!(flow.corrupted.is_none()); } }
Since 11.7.0 the probe reads the whole datagram (#184). Until 11.6.0 it saw only the first PROBE_CAP bytes, 18 KiB. Blocks that ended exactly at byte 18 432 were then enough, whatever came after, and a valid datagram with a block across that bound stayed "Unknown". The label now vouches for the datagram that AsterixPacket::try_from decodes. The cost stays linear: decoding 65 505 bytes of ASTERIX records takes 2.7 ms in release, 3.8 times the cost of the 18 432 bytes of the old cap. Surveillance datagrams are far smaller, 1 393 bytes at most in the corpus.
Verified against tshark, record by record
tests/asterix_golden.rs replays the nine files of pcaps_exemple/protocols/asterix/ (see its SOURCE.md):
- the maintainer's anonymized CAT 048 capture, 203 datagrams on ports 8611 and 8612;
- three samples of Croatia Control: a CAT 034/048 capture (100 datagrams, 20 of them with two blocks), a CAT 062/065 datagram, and a raw stream of two CAT 021 blocks (
cat21_re.ast); - five attachments of the Wireshark tracker:
wireshark_8579_radardata.pcap, 50 000 frames of a control network with 41 928 ASTERIX datagrams on 18 multicast streams;wireshark_9953_cat021023.pcap, 1 588 datagrams of CAT 021, 023 and 247;wireshark_9624_cat62_re.pcap, 668 datagrams of CAT 062 with their Reserved Expansion Field, some followed by a CAT 065 block; and the two CAT 008 captures of issue 9239, 9 and 10 datagrams.
For every record of every frame, the sequence of items and the length of the record are compared with an oracle produced from tshark 4.6.6 -V by tools/asterix_oracle.py, frames of the same shape grouped (tests/data/asterix_tshark_oracle.tsv): 44 411 frames in parity, which carry
| CAT | 001 | 002 | 008 | 021 | 023 | 034 | 048 | 062 | 063 | 065 | 247 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| data blocks | 29 520 | 19 512 | 67 | 1 555 | 30 | 7 913 | 7 484 | 7 759 | 307 | 1 526 | 3 |
| records | 65 146 | 19 677 | 67 | 1 555 | 30 | 7 913 | 33 665 | 16 434 | 331 | 1 526 | 3 |
The 96 other frames of radardata.pcap are those where tshark stumbles (tests/data/asterix_tshark_limits.tsv). Each carries a CAT 002 record whose I002/050 takes two octets: tshark reads one, then takes the other for a parasite record read beyond the block (26 frames) or declares the frame malformed (70). The crate follows the specification and decodes these records whole; the test expects the shape tshark gives without the parasite record, I002/050 counting for two octets. On frame 30453 (tested):
#![allow(unused)] fn main() { #[test] fn where_tshark_stops_the_specification_goes_on() { // Frame 30453 of wireshark_8579_radardata.pcap: a CAT 002 north marker // whose I002/050 takes two octets. tshark 4.6.6 reads one and calls // the frame malformed. let raw = hex::decode(RADARDATA_FRAME_30453_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "ASTERIX"); let packet = AsterixPacket::try_from(flow.transport.as_ref().unwrap().payload.unwrap()).unwrap(); let record = &packet.blocks[0].records[0]; let ids: Vec<&str> = record.items.iter().map(|item| item.id).collect(); assert_eq!(ids, ["I002/010", "I002/000", "I002/030", "I002/050"]); assert_eq!(record.item("I002/050"), Some(&[0x0b, 0x02][..])); // FX 1, then FX 0 assert_eq!(uap::CAT002.item(6).unwrap().format, ItemFormat::Variable); } }
The typed values are cross-checked with the -V output of tshark on real frames, in the unit tests of the catNNN modules and, for CAT 048 and 034, in the golden test. The golden histogram of pcaps_exemple/protocols/ (tests/golden_pcaps.rs) counts 44 507 ASTERIX datagrams, exactly the 44 411 and the 96 of the two oracle files: no frame of another folder comes out ASTERIX. The eight new categories moved that count from 13 739, and "Unknown" from 40 177 to 9 409: the 30 047 datagrams of radardata.pcap that carry one of them, and 721 in the other captures (668 of cat62_re, 33 CAT 023/247 datagrams of cat021023, 19 of the two CAT 008 captures, 1 of cat_062_065).
The fuzz target parse_asterix covers the eleven categories and both UAPs of CAT 001. On whatever it decodes, it asserts that the block lengths add up to the input, that every record has an item and a UAP, that every item and every RFS item is non-empty and lies inside the buffer, that subfields 1 to 4 of an item, when present, lie inside it too, that the FSPECs and items of a block cover its length exactly, and it runs every typed decoder on every record.
Validations
All of them are AsterixError, in packet_parser::errors::application::asterix; the last four are new in 11.6.0:
| Error | When |
|---|---|
Truncated { needed, actual } | fewer than 3 bytes where a data block must start |
InvalidBlockLength { category, declared, available } | a LEN below 5, or beyond the bytes left |
UnsupportedCategory(u8) | a category without a UAP |
EmptyRecord { category } | an FSPEC that announces no item |
FspecOverflow { category } | an FSPEC longer than the UAP allows, or whose FX never drops |
UnknownFrn { category, frn } | an FSPEC bit on a reserved FRN, or beyond the UAP |
UnknownSubfield { item, subfield } | a primary subfield bit on a spare subfield, or beyond the item |
InvalidExplicitLength { item } | an explicit item (RE, SP) of length 0 |
TruncatedItem { item, needed, actual } | an item, a subfield or an RFS item that overflows its block |
BlockNotConsumed { category } | declared, never returned (see below) |
ExtentOverflow { item } | an extended item whose last defined extent sets FX |
EmptyRfs { category } | an RFS field that announces no item |
InvalidRfsFrn { category, frn } | an RFS item whose FRN names no item of the UAP, or the RFS itself |
DuplicateRfsFrn { category, frn } | an RFS item the FSPEC already announces, or that the field carries twice |
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- Other categories. A category outside the eleven, CAT 010, 019, 020 or 240 for instance, is
UnsupportedCategoryand refuses its datagram; the corpus has no capture of them. - Other editions. One UAP per category, from the latest edition, which accepts the earlier ones. The CAT 021 editions 0.2x, whose UAP is entirely different from 2.x, are not described: nothing in the bytes tells the editions apart, and the crate decodes 2.x. The CAT 247 reports of
cat021023.pcapannounce CAT 021 edition 0.26, yet its 1 555 CAT 021 records cut cleanly along the 2.x UAP, for the crate as for tshark. - Item contents beyond the typed subset:
REandSPstay opaque, BDS registers and weather vectors are raw bytes, the subfields of a compound item are cut and reachable by number, most of them not interpreted. - CAT 001 tracks and RFS fields occur in no capture of the corpus: only the crate's unit tests, on synthetic bytes, decode them.
AsterixError::BlockNotConsumedis declared but never returned: its onereturn, for a block without a record, cannot be reached, since a block of at least 5 bytes always yields a record or a more precise error.
BACnet/IP
BACnet (ASHRAE 135, A Data Communication Protocol for Building Automation and Control Networks) is the protocol of building automation, and annex J carries it over UDP as BACnet/IP. Decoded since 11.6.0 (#159), as part of epic #102 with IEC 60870-5-104 and GOOSE. The module is packet_parser::parse::application::protocols::bacnet: it reads the three layers of a datagram, the BVLC, the NPDU and the APDU, and stops at the service data, which stays tag-encoded bytes.
Detection: its ports, then any UDP port
Two rules of the dispatch table, 27 and 45, share one probe, ProbeId::Bacnet:
#![allow(unused)] fn main() { // among the port rules, right after RADIUS port_rule(ApplicationProtocol::BacnetIp, Guard::Udp, is_bacnet_udp_port, ProbeId::Bacnet), // 47808..=47823 // in the blind cascade, after DNP3 and RADIUS, before Bitcoin rule(ApplicationProtocol::BacnetIp, Guard::Udp, ProbeId::Bacnet), }
is_bacnet_udp_port matches 47808 to 47823, 0xBAC0 to 0xBACF, on either side: 47808 is the IANA bacnet port, and the crate's source ties the fifteen others to the multiple networks of annex J (tshark registers BVLC on 47808 alone). The probe is BacnetPacket::try_from(payload).is_ok(), run on the whole payload, as every probe but the four text ones since 11.7.0 (#185): the BVLC length is compared with the real datagram. It accepts a datagram only if:
- the first byte, the BVLC type, is
0x81; - the function is one of the thirteen of annex J,
0x00to0x0C; - the BVLC length is the length of the datagram, to the byte;
- for the four functions that carry an NPDU, the NPDU has version 1, the addresses and the hop count its control byte announces, and then either a network message or an APDU of type 0 to 7 with the fixed fields of its type.
The crate considers this constrained enough to do without the port, so the same probe runs blind on any UDP datagram that no earlier rule has claimed, and there is no DecodeAsProtocol variant for BACnet: a device on another port is recognized anyway. Both rules are Guard::Udp; the same bytes in a TCP segment never get the label.
Since the two rules share the probe, a datagram on 47808 that fails it is not probed again by the blind rule: it goes on down the table, usually to "Unknown". A refusal never fills corrupted: on UDP a port is a hint, not an announcement, as for PTP. Every datagram of the corpus has 47808 on one side; the blind route is checked by moving frame 3 of iti_bacnet_test.pcap to other ports (tested):
#![allow(unused)] fn main() { #[test] fn bacnet_is_recognized_off_its_ports_and_refused_when_altered() { // Frame 3 moved to UDP 40000 -> 40001: no port rule applies, the // blind rule recognizes the datagram by its content. let mut raw = hex::decode(ITI_READ_PROPERTY_HEX).unwrap(); raw[34..38].copy_from_slice(&[0x9c, 0x40, 0x9c, 0x41]); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let transport = flow.transport.as_ref().unwrap(); assert_eq!((transport.source_port, transport.destination_port), (Some(40000), Some(40001))); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "BACnet/IP"); // One altered byte: the decoder refuses the datagram, the label is not // given, and nothing is reported as corrupted. let start = raw.len() - 17; // where the BVLC header starts for (offset, value, error) in [ (0, 0x82, BacnetParseError::InvalidBvlcType(0x82)), (3, 0x12, BacnetParseError::LengthMismatch { declared: 18, actual: 17 }), (4, 0x02, BacnetParseError::UnsupportedNpduVersion(2)), ] { let mut altered = raw.clone(); altered[start + offset] = value; assert_eq!(BacnetPacket::try_from(&altered[start..]), Err(error)); let flow = parse(LinkType::ETHERNET, &altered).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "Unknown"); assert!(flow.corrupted.is_none()); } } }
The datagram
#![allow(unused)] fn main() { pub struct BacnetPacket<'a> { pub bvlc: BvlcHeader, pub forwarded_from: Option<(Ipv4Addr, u16)>, // Forwarded-NPDU: the original sender pub npdu: Option<Npdu<'a>>, // for the functions that carry one pub body: &'a [u8], // after the header (and the origin) } pub struct BvlcHeader { pub function: u8, pub kind: BvlcFunction, pub length: u16, // the whole datagram } }
Every struct and enum of the module is #[non_exhaustive], and every byte field borrows the datagram: decoding allocates nothing.
| Bytes | Field | Note |
|---|---|---|
| 0 | type | 0x81; checked, not kept |
| 1 | function, kind | the code and its BvlcFunction |
| 2–3 | length | big-endian, header included: must equal the datagram |
| 4–9 | forwarded_from | Forwarded-NPDU only: IPv4 address and UDP port of the original sender |
| then | body | the rest: the NPDU, or the data of the function |
| Code | BvlcFunction | NPDU |
|---|---|---|
0x00 | Result | — |
0x01 | WriteBroadcastDistributionTable | — |
0x02 | ReadBroadcastDistributionTable | — |
0x03 | ReadBroadcastDistributionTableAck | — |
0x04 | ForwardedNpdu | after the 6-byte origin |
0x05 | RegisterForeignDevice | — |
0x06 | ReadForeignDeviceTable | — |
0x07 | ReadForeignDeviceTableAck | — |
0x08 | DeleteForeignDeviceTableEntry | — |
0x09 | DistributeBroadcastToNetwork | yes |
0x0A | OriginalUnicastNpdu | yes |
0x0B | OriginalBroadcastNpdu | yes |
0x0C | SecureBvll | — |
For the four functions that carry an NPDU, body holds the bytes npdu decodes. For the nine others npdu is None and body is their data, undecoded: a result code, a time-to-live, a table; a Secure-BVLL is recognized and left whole in body. BvlcFunction::from_code is public. A registration and its answer (tested):
#![allow(unused)] fn main() { #[test] fn bacnet_bvlc_functions_without_an_npdu() { // Frame 25: a device asks to be registered as a foreign device. let raw = hex::decode(ITI_REGISTER_FOREIGN_DEVICE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "BACnet/IP"); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = BacnetPacket::try_from(payload).unwrap(); assert_eq!(packet.bvlc.kind, BvlcFunction::RegisterForeignDevice); assert_eq!(packet.bvlc.length, 6); assert_eq!(packet.npdu, None); assert_eq!(packet.body, &[0x00, 0x10]); // time-to-live, 16 seconds // Frame 26: the BVLC-Result. Its code is left in `body`, undecoded // (tshark reads 0x0030, Register-Foreign-Device NAK). let raw = hex::decode(ITI_BVLC_RESULT_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = BacnetPacket::try_from(payload).unwrap(); assert_eq!(packet.bvlc.kind, BvlcFunction::Result); assert_eq!(packet.npdu, None); assert_eq!(packet.body, &[0x00, 0x30]); } }
The NPDU
#![allow(unused)] fn main() { pub struct Npdu<'a> { pub version: u8, // 1 pub control: u8, // the raw byte pub destination: Option<NetworkAddress<'a>>, // DNET, DLEN, DADR pub source: Option<NetworkAddress<'a>>, // SNET, SLEN, SADR pub hop_count: Option<u8>, // present with a destination pub message: NpduMessage<'a>, } pub struct NetworkAddress<'a> { pub network: u16, pub address: &'a [u8], // MAC address, empty for a broadcast } pub enum NpduMessage<'a> { Network { message_type: u8, vendor_id: Option<u16>, data: &'a [u8] }, Apdu(Apdu<'a>), } }
The NPDU is the network layer of BACnet, the one that routes between BACnet networks. After its two fixed bytes, what follows depends on the control byte, so the fields have sizes, not offsets:
| Field | Bytes | Present when |
|---|---|---|
version | 1 | always; must be 1 |
control | 1 | always |
destination | 2 + 1 + DLEN | control bit 0x20 |
source | 2 + 1 + SLEN | control bit 0x08 |
hop_count | 1 | a destination is present |
message_type | 1 | control bit 0x80, then a 2-byte vendor_id for types 0x80 and above |
| the rest | the network message data, or the APDU |
| Control bit | Meaning | Read through |
|---|---|---|
0x80 | a network-layer message, not an APDU | NpduMessage::Network |
0x40 | reserved | not checked |
0x20 | destination specifier | destination, hop_count |
0x10 | reserved | not checked |
0x08 | source specifier | source |
0x04 | expecting reply | expecting_reply() |
0x03 | priority | priority(): 0 normal, 1 urgent, 2 critical equipment, 3 life safety |
A destination network of 65535 is a global broadcast, and an empty address a broadcast on the destination network. Network messages are typed by number only: message_type, the vendor_id of a proprietary type, and the data, raw. NpduMessage is #[non_exhaustive]: a match on it needs a _ arm. A Who-Is broadcast to every network, then a network message of the same segment (tested):
#![allow(unused)] fn main() { #[test] fn bacnet_who_is_and_a_network_message_broadcast_to_all_networks() { // Frame 10: a Who-Is for every device on every network. let raw = hex::decode(NDPI_WHO_IS_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "BACnet/IP"); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = BacnetPacket::try_from(payload).unwrap(); assert_eq!(packet.bvlc.kind, BvlcFunction::OriginalBroadcastNpdu); let npdu = packet.npdu.unwrap(); assert_eq!(npdu.control, 0x20); // destination specifier let destination = npdu.destination.unwrap(); assert_eq!(destination.network, 65535); // DNET 0xFFFF assert!(destination.address.is_empty()); // DLEN 0 assert_eq!(npdu.source, None); assert_eq!(npdu.hop_count, Some(255)); // present with a destination let NpduMessage::Apdu(who_is) = npdu.message else { panic!("expected an APDU, got {:?}", npdu.message); }; assert_eq!(who_is.kind, ApduType::UnconfirmedRequest); assert_eq!(who_is.invoke_id, None); // nothing to pair with assert_eq!(who_is.unconfirmed_service(), Some(UnconfirmedService::WhoIs)); assert_eq!(who_is.confirmed_service(), None); assert!(who_is.data.is_empty()); // no device instance range // Frame 22: control 0xA0, a network-layer message instead of an APDU. let raw = hex::decode(NDPI_NETWORK_MESSAGE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = BacnetPacket::try_from(payload).unwrap(); let npdu = packet.npdu.unwrap(); assert_eq!((npdu.control, npdu.hop_count), (0xa0, Some(255))); let NpduMessage::Network { message_type, vendor_id, data } = npdu.message else { panic!("expected a network message, got {:?}", npdu.message); }; assert_eq!(message_type, 0x01); // I-Am-Router-To-Network, for tshark assert_eq!(vendor_id, None); // only types 0x80 and above have one assert_eq!(data, &[0x00, 0x00]); // the network list, raw } }
The APDU
#![allow(unused)] fn main() { pub struct Apdu<'a> { pub apdu_type: u8, // high nibble of the first byte pub kind: ApduType, pub flags: u8, // low nibble, as is pub invoke_id: Option<u8>, // absent from an unconfirmed request pub max_segments_and_apdu: Option<u8>, // confirmed request: the raw byte pub segment: Option<(u8, u8)>, // sequence number, window size pub service: Option<u8>, // service choice pub reason: Option<u8>, // reject or abort reason pub data: &'a [u8], // the service data, tag-encoded } }
The type says which fixed fields follow the first byte; whatever comes after them is data:
| Type | ApduType | Fields, in wire order |
|---|---|---|
| 0 | ConfirmedRequest | max_segments_and_apdu, invoke_id, segment if SEG, service |
| 1 | UnconfirmedRequest | service |
| 2 | SimpleAck | invoke_id, service |
| 3 | ComplexAck | invoke_id, segment if SEG, service |
| 4 | SegmentAck | invoke_id, segment |
| 5 | Error | invoke_id, service |
| 6 | Reject | invoke_id, reason |
| 7 | Abort | invoke_id, reason |
flags is the low nibble of the first byte: SEG 0x08 and MOR 0x04 in a ConfirmedRequest or a ComplexACK, SA 0x02 in a ConfirmedRequest, NAK 0x02 and SRV 0x01 in a SegmentACK, SRV 0x01 in an Abort. The decoder itself reads only SEG, which says whether a sequence number and a window follow; the other bits are left to the caller.
confirmed_service() names the service of a ConfirmedRequest, SimpleAck, ComplexAck or Error among the 36 of ConfirmedService (0 AcknowledgeAlarm to 35 DirectoryQuery), and unconfirmed_service() that of an UnconfirmedRequest among the 15 of UnconfirmedService (0 IAm to 14 YouAre). An unknown code is not an error: service keeps the byte and the method returns None. Both enums have a public from_code.
The last two confirmed services came in 11.7.0 (#190), at the end of the enum: 34 AuthRequest, auth-request, from addendum 135-2020cp (protocol revision 29, incorporated into ANSI/ASHRAE 135-2024), and 35 DirectoryQuery, directory-query, from addendum 135-2024cu (protocol revision 31). Before 11.7.0, from_code returned None for both codes. tshark 4.6.6 names the first, authRequest (34), and not the second. No datagram of the corpus carries either.
A readProperty, the ComplexACK that answers it, and the two new codes (tested):
#![allow(unused)] fn main() { #[test] fn bacnet_read_property_and_its_complex_ack() { // Frame 3: labelled by the port rule, then decoded from the payload. let raw = hex::decode(ITI_READ_PROPERTY_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "BACnet/IP"); let transport = flow.transport.as_ref().unwrap(); assert_eq!(transport.destination_port, Some(47808)); let packet = BacnetPacket::try_from(transport.payload.unwrap()).unwrap(); assert_eq!(packet.bvlc.kind, BvlcFunction::OriginalUnicastNpdu); assert_eq!((packet.bvlc.function, packet.bvlc.length), (0x0a, 17)); // the whole datagram assert_eq!(packet.forwarded_from, None); let npdu = packet.npdu.unwrap(); assert_eq!((npdu.version, npdu.control), (1, 0x04)); assert!(npdu.expecting_reply()); assert_eq!(npdu.priority(), 0); // normal assert!(npdu.destination.is_none() && npdu.source.is_none()); assert_eq!(npdu.hop_count, None); // no destination, no hop count let NpduMessage::Apdu(request) = npdu.message else { panic!("expected an APDU, got {:?}", npdu.message); }; assert_eq!(request.kind, ApduType::ConfirmedRequest); assert_eq!(request.flags, 0); // not segmented assert_eq!(request.max_segments_and_apdu, Some(0x05)); // up to 1476 bytes, for tshark assert_eq!(request.invoke_id, Some(1)); assert_eq!(request.service, Some(12)); assert_eq!(request.confirmed_service(), Some(ConfirmedService::ReadProperty)); // The object and the property asked for, tag-encoded, left as bytes. assert_eq!(request.data, &[0x0c, 0x02, 0x3f, 0xff, 0xff, 0x19, 0x4b]); // Frame 4: the answer carries the same invoke id and service. let raw = hex::decode(ITI_COMPLEX_ACK_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = BacnetPacket::try_from(payload).unwrap(); let npdu = packet.npdu.unwrap(); assert!(!npdu.expecting_reply()); let NpduMessage::Apdu(ack) = npdu.message else { panic!("expected an APDU, got {:?}", npdu.message); }; assert_eq!(ack.kind, ApduType::ComplexAck); assert_eq!((ack.invoke_id, ack.service), (Some(1), Some(12))); assert_eq!(ack.max_segments_and_apdu, None); // a request field assert_eq!(ack.segment, None); assert_eq!(ack.data.len(), 14); // object and property again, then the value // Past the corpus: the codes 34 and 35 are named since 11.7.0, 36 is not. assert_eq!(ConfirmedService::from_code(34), Some(ConfirmedService::AuthRequest)); assert_eq!(ConfirmedService::from_code(35), Some(ConfirmedService::DirectoryQuery)); assert_eq!(ConfirmedService::from_code(36), None); } }
Validations
All of them are BacnetParseError, in packet_parser::errors::application::bacnet:
| Error | When |
|---|---|
Truncated { expected, actual } | a part is shorter than its fixed fields: the 4-byte BVLC header, the origin of a Forwarded-NPDU, the NPDU header, a network address, the hop count, a network message, the fields of an APDU type; both numbers count from the start of what is being read: the datagram for the BVLC header, the BVLC body for the origin, the NPDU for its header and its hop count, and otherwise the address, the network message or the APDU itself |
InvalidBvlcType(u8) | the first byte is not 0x81; BACnet/IPv6 (annex U), type 0x82 for tshark, ends here |
UnknownBvlcFunction(u8) | a function above 0x0C |
LengthMismatch { declared, actual } | a BVLC length other than the datagram's, trailing bytes included; the Ethernet padding of a short frame is not part of the datagram (frames 1 to 9 of ndpi_bacnet.pcap carry one byte of it) |
UnsupportedNpduVersion(u8) | an NPDU version other than 1 |
UnknownApduType(u8) | an APDU type above 7 |
In the pipeline, every one of them means the same thing: the label is not given, as the detection section shows.
Oracle: 45 datagrams, field by field
The golden test tests/bacnet_golden.rs runs the two captures of pcaps_exemple/protocols/bacnet/ and compares every datagram with tshark 4.6.6, frozen in tests/data/bacnet_tshark_oracle.tsv by tools/bacnet_oracle.sh: ports and payload length, BVLC function and length, NPDU version, control, destination and source networks and address lengths, hop count, network message type, APDU type, invoke id, confirmed or unconfirmed service. The 45 datagrams that carry a BVLC are all labelled "BACnet/IP"; the four empty UDP datagrams of the ITI capture stay without application.
| Capture | Datagrams | Content | Origin |
|---|---|---|---|
iti_bacnet_test.pcap | 22 of 26 frames | a host queries a Johnson Controls controller (MS-NAE4510-2): the nine readProperty of nmap's bacnet-info script, byte for byte, all on the device object, and their ComplexACK; a Read-Broadcast-Distribution-Table and a Register-Foreign-Device, both answered by a BVLC-Result | ITI ICS-Security-Tools, CC-BY-4.0 |
ndpi_bacnet.pcap | 23 | nine readProperty that Internet scanners send to seven exposed addresses of one network, then a local network: Who-Is, I-Am, an Error, two network messages | nDPI test corpus, LGPL-3.0 |
Over the 45: 27 Original-Unicast-NPDU, 14 Original-Broadcast-NPDU, two BVLC-Results, one Read-Broadcast-Distribution-Table and one Register-Foreign-Device; 18 ConfirmedRequest, 11 UnconfirmedRequest, 9 ComplexACK and one Error APDU, plus two network messages. One column is compared after a translation: tshark's bvlc.length is the size of the BVLC header it consumed (4, or 10 with the origin of a Forwarded-NPDU) when an NPDU follows, and the whole message otherwise; the test rebuilds that value, while the wire field is checked against the datagram by the decoder itself. A second test moves frame 3 of the ITI capture to ports 40000 and 40001, where only the blind rule can label it, then alters one byte at a time (BVLC type, function, length, NPDU version, APDU type): the decoder refuses each of the five, and the label goes.
A run of the 11.6.0 pipeline over the 386 403 frames that the crate's test reader gets from the captures tracked under pcaps_exemple/ gives the label "BACnet/IP" to these 45 datagrams and to nothing else: the very frames tshark dissects as BVLC. The fuzz target parse_bacnet runs nightly, on its input and on mutations of four real datagrams: whatever it decodes must have the input's length as BVLC length, a hop count exactly when it has a destination, a vendor id exactly on network message types 0x80 and above, and its body and data inside the input.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- Service data stays tag-encoded bytes in
Apdu::data: object identifiers, property values, the device range of a Who-Is, the content of an I-Am. The crate decodes the envelope, not the application tags. - Network messages and BVLC control functions are typed, not decoded:
message_typeanddata, the result codes, times-to-live and tables inbody. A Secure-BVLL is recognized and left whole. - No state: no reassembly of segmented messages, no pairing of a request with its acknowledgement by invoke id. One datagram at a time, as in the rest of the crate.
- Annex J only: BACnet/IPv6 is refused as
InvalidBvlcType, and the other data links of the standard reach no decoder. - The two reserved bits of the NPDU control,
0x40and0x10, are not checked: a datagram with one of them set is decoded and labelled like any other. - Paths no capture exercises: the corpus has no segmented message, no SimpleACK, SegmentACK, Reject or Abort, no source address, no Forwarded-NPDU and no proprietary network message. These follow the standard; the last two are checked by unit tests on built bytes, the Forwarded-NPDU wrapped around frame 3.
DCE/RPC
DCE/RPC (DCE 1.1: Remote Procedure Call, Open Group C706) is the remote procedure call of Windows: MSRPC and DCOM run on it. A client binds to an interface, then calls its operations by number. The decoder reads the connection-oriented form, the one that runs over TCP. It was added in 13.3.0 (#356, PR #361). The module is packet_parser::parse::application::protocols::dcerpc, the errors are DceRpcError, in packet_parser::errors::application::dcerpc, and the label is "DCE/RPC".
#![allow(unused)] fn main() { pub struct DceRpcPdu<'a> { pub version_minor: u8, // 0 or 1; the major version is 5 pub pdu_type: DceRpcPduType, pub flags: u8, // pfc_flags pub little_endian: bool, // from the data representation label pub data_representation: [u8; 4], pub frag_length: u16, // the whole fragment, header included pub auth_length: u16, // the authentication value that ends it pub call_id: u32, pub body: &'a [u8], // what follows the 16-byte header // private: the bytes of the segment after the fragment } pub struct DceRpcRequest { pub alloc_hint: u32, pub context_id: u16, // presentation context, set by the Bind pub opnum: u16, // operation number within the interface } }
Both structs are #[non_exhaustive], and body borrows from the segment. The header says in which byte order its own integers are written: the first byte of the data representation label is 0x10 for little-endian, what Windows sends, 0x00 for big-endian. The decoder reads frag_length, auth_length, call_id and the request fields in that order, and little_endian keeps it for the caller.
| Method | Gives |
|---|---|
is_first_fragment(), is_last_fragment() | bits 0x01 and 0x02 of flags: a call that fits in one fragment has both |
is_truncated() | true when the fragment goes on in the next TCP segment |
rest() | the bytes of the segment after the fragment: another PDU, or nothing |
request() | the three fields of a Request; None for another type, or when the segment stops before them |
DceRpcPduType names the twelve connection-oriented types, and as_u8() gives the byte back:
| Code | Variant | Code | Variant |
|---|---|---|---|
| 0 | Request | 14 | AlterContext |
| 2 | Response | 15 | AlterContextResponse |
| 3 | Fault | 16 | Auth3 |
| 11 | Bind | 17 | Shutdown |
| 12 | BindAck | 18 | CoCancel |
| 13 | BindNak | 19 | Orphaned |
A client that asks the endpoint mapper of a server where a service listens starts with a Bind (tested):
#![allow(unused)] fn main() { #[test] fn a_bind_and_its_common_header() { let raw = hex::decode(BIND_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("DCE/RPC")); let pdu = DceRpcPdu::try_from(payload(&flow)).unwrap(); assert_eq!(pdu.version_minor, 0); assert_eq!(pdu.pdu_type, DceRpcPduType::Bind); assert_eq!(pdu.pdu_type.as_u8(), 11); // One fragment holds the whole PDU: first and last at once. assert_eq!(pdu.flags, 0x03); assert!(pdu.is_first_fragment() && pdu.is_last_fragment()); // The label says little-endian, ASCII, IEEE: what Windows sends. assert_eq!(pdu.data_representation, [0x10, 0, 0, 0]); assert!(pdu.little_endian); assert_eq!((pdu.frag_length, pdu.auth_length), (160, 0)); assert_eq!(pdu.call_id, 2); // The body is what follows the 16 bytes of the header: here the // three presentation contexts, borrowed and not decoded. assert_eq!(pdu.body.len(), 160 - DCERPC_COMMON_HEADER_LENGTH); assert!(!pdu.is_truncated()); assert!(pdu.rest().is_empty()); // Only a Request has an operation number. assert_eq!(pdu.request(), None); } }
The Request follows, with the number of the operation (tested):
#![allow(unused)] fn main() { #[test] fn a_request_and_its_operation() { let raw = hex::decode(REQUEST_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("DCE/RPC")); let pdu = DceRpcPdu::try_from(payload(&flow)).unwrap(); assert_eq!(pdu.pdu_type, DceRpcPduType::Request); // The same call identifier as the Bind: one association. assert_eq!(pdu.call_id, 2); let request = pdu.request().unwrap(); // 144 bytes of stub data, in presentation context 1, the second // one the Bind offered. assert_eq!(request.alloc_hint, 144); assert_eq!(request.context_id, 1); // Operation 3 of the endpoint mapper is ept_map. The crate gives // the number; the name belongs to the interface. assert_eq!(request.opnum, 3); assert_eq!(pdu.body.len(), 8 + 144); } }
The body is not decoded: the presentation contexts of a Bind, the stub data of a call, in NDR, and the authentication verifier are returned as bytes. An operation number means something only with the interface the Bind chose, and the crate keeps no state to remember it.
Detection: any TCP port
| Where | Rule | Probe | Accepts |
|---|---|---|---|
| any TCP port | blind rule 77 | ProbeId::DceRpc | a PDU DceRpcPdu::try_from accepts, followed by nothing or by a second PDU it accepts |
DCE/RPC has no fixed port. TCP 135 is the endpoint mapper, a directory: it answers with the port of the service, drawn from a dynamic range, and the calls go there. A port rule would see the directory and miss the calls. Rule 77 sits at the end of the blind cascade of the table, after NMF and before MQTT.
The common header is enough to stand on, because sixteen bytes leave little freedom:
- the version,
05 00or05 01; - a PDU type among twelve values;
- a data representation label whose four bytes take few values: two byte orders, two character sets, four floating-point formats, and two reserved bytes that are null;
- a fragment length, read in the byte order the label announced, that covers at least the header of its type;
- an authentication length that fits in the fragment.
When the fragment ends before the segment does, what follows must be a PDU too: one segment may hold two. A fragment longer than its segment is accepted, the rest being in the next one.
There is no DecodeAsProtocol variant: the rule has no port guard, so it already runs on every TCP port.
Validations
| Part | Check | Error |
|---|---|---|
| Segment | at least the 16 bytes of the common header | DceRpcError::TooShort { expected, actual } |
| Version | 5.0 or 5.1 | UnsupportedVersion { major, minor } |
| PDU type | one of the twelve | UnknownPduType |
| Data representation | a byte order of 0 or 1, a character set of 0 or 1, a floating-point format of 0 to 3, two null bytes | InvalidDataRepresentation |
| Fragment length | at least the header and the fixed fields of the type | FragmentTooShort { frag_length, minimum } |
| Authentication length | when not zero, the value and its eight-byte trailer fit after those fields | InvalidAuthLength { auth_length, frag_length } |
The checks run in this order, and the first failure is the error. The fixed fields are 8 bytes for a Request, a Response, a Bind, a Bind Ack and both Alter Context PDUs, 16 for a Fault, and none for the five others. What the decoder refuses, and the one cut it accepts (tested):
#![allow(unused)] fn main() { #[test] fn what_dcerpc_refuses() { let raw = hex::decode(BIND_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let bind = payload(&flow); // Less than the common header. assert_eq!( DceRpcPdu::try_from(&bind[..10]).unwrap_err(), DceRpcError::TooShort { expected: 16, actual: 10 } ); // The same bytes read one byte late: no version 0.11. assert_eq!( DceRpcPdu::try_from(&bind[1..]).unwrap_err(), DceRpcError::UnsupportedVersion { major: 0, minor: 11 } ); // A segment that stops before the end of its fragment is still a // PDU: the header is whole, the body is cut. let pdu = DceRpcPdu::try_from(&bind[..100]).unwrap(); assert!(pdu.is_truncated()); assert_eq!(pdu.body.len(), 84); } }
What is not DCE/RPC
Each row was checked against the crate, on a TCP port without a rule of its own:
| Payload | Label | Why |
|---|---|---|
| the Bind of the example | "DCE/RPC" | |
| its first 100 bytes | "DCE/RPC" | a fragment cut by its segment |
| its first 10 bytes | "Unknown" | TooShort |
| the Bind twice in one segment | "DCE/RPC" | two PDUs |
the Bind followed by hello | "Unknown" | what follows a fragment must be a PDU |
| its version changed to 4 | "Unknown" | UnsupportedVersion: 4 is the connectionless form |
| its type changed to 1 | "Unknown" | UnknownPduType: a connectionless type |
| a reserved byte of its label set to 1 | "Unknown" | InvalidDataRepresentation |
| its fragment length changed to 10 | "Unknown" | FragmentTooShort |
| its authentication length changed to 255 | "Unknown" | InvalidAuthLength |
| the Bind, on UDP | "Unknown" | the guard is TCP |
Oracle: 385 segments
The golden test tests/dcerpc_golden.rs compares the crate with tshark 4.6.9, its TCP and DCE/RPC reassembly switched off. tools/dcerpc_oracle.sh freezes, in tests/data/dcerpc_tshark_oracle.tsv, one line per segment that tshark dissects as DCE/RPC over TCP: the minor version, the PDU type, the flags, the data representation, the two lengths, the call identifier and the operation number. No capture was added: the 385 segments are in The-Ultimate-PCAP.pcapng, calls between Windows machines, with and without authentication.
| PDU | Segments |
|---|---|
| Request | 135 |
| Response | 134 |
| Alter Context and its response | 31 and 31 |
| Bind and Bind Ack | 27 and 27 |
The test checks, for each segment, every field of the oracle, and that request() gives the operation number of the 135 Requests. Sixteen fragments are longer than their segment, and is_truncated() says so for exactly those.
The crate labels fourteen segments more than tshark. They are TCP retransmissions: tshark recognizes them from the sequence numbers and does not hand them to its dissector, and a stateless parser reads them like any other segment (Limits). The test names them one by one. No other frame of the capture gets the label, the DCE/RPC that travels inside SMB included, and no frame of the captures under pcaps_exemple/protocols/ does.
What is left out
The limits every protocol shares are on the Limits page. The ones below are this protocol's own.
- Continuation segments. The segments that carry the rest of a truncated fragment are
"Unknown". - The second PDU of a segment is checked by the probe and not decoded:
rest()gives its bytes, andDceRpcPdu::try_fromreads them. - Fragments are not reassembled. A call split over several fragments is several PDUs with the same
call_id. - The interface. The crate reads no UUID from a Bind and keeps no association between a context and an interface: an operation number has no name.
- The body. NDR, the authentication trailer and the object UUID that
pfc_flagsmay announce are not decoded. - Connectionless DCE/RPC, version 4, over UDP, and DCE/RPC inside SMB named pipes or HTTP are not read.
DIS
Distributed Interactive Simulation, IEEE 1278.1, added in 11.6.0 (#123) as part of the defense lot (#125): the protocol that links military simulators, carrying the position of each entity, fire, simulated radios and the environment. The PDU formats are openly documented by the Open-DIS project, the enumerations by SISO-REF-010. The module is packet_parser::parse::application::protocols::dis.
A UDP datagram carries one or more PDUs, each behind the same 12-byte header. The decoder names every PDU, decodes three bodies into typed values, Entity State, Transmitter and Signal, and keeps the other bodies as bytes.
Detection: a customary port and a strict blind probe
Like ASTERIX, DIS has neither a magic nor an IANA port. UDP 3000 is the customary one, the port Wireshark registers for DIS by default; the corpus also carries DIS on 6993 and 22999. The dispatch table has two rules for it, which read the same bytes in two ways:
#![allow(unused)] fn main() { // among the port rules, right after PTP: UDP 3000 on either side port_rule(ApplicationProtocol::Dis, Guard::Udp, is_dis_udp_port, ProbeId::DisLenient), // in the blind cascade, after ASTERIX and before DNP3 rule(ApplicationProtocol::Dis, Guard::Udp, ProbeId::Dis), }
with the probes
#![allow(unused)] fn main() { ProbeId::Dis => DisPacket::try_from(payload).is_ok(), ProbeId::DisLenient => DisPacket::try_from_lenient(payload).is_ok(), }
- The blind probe is
DisPacket::try_from, the strict read: every PDU must be valid (a version from 1 to 7, a type from 1 to 72, a family of the standard or an experimental one, a length that covers the header and stays within the datagram, the fixed fields of a typed body), and the PDUs must tile the datagram to the last byte. This exact tiling is the signature that lets the blind rule label DIS without a port guard. It is still not reached on the terminal mDNS and LLMNR ports, UDP 5353 and 5355, where a failed probe ends the dispatch with no label. - On UDP 3000 the port already says DIS, and the probe is
DisPacket::try_from_lenient: a declared length shorter than the datagram is accepted, and the rest is kept intrailing. Three real PDUs of the corpus declare 48 bytes in a 160-byte datagram, and tshark dissects them without stopping at the length. - On another port,
ParseConfig::decode_as(port, DecodeAsProtocol::Dis)gives the same lenient read: the variant maps to(ApplicationProtocol::Dis, Guard::Udp, ProbeId::DisLenient), evaluated before the table like every Decode As port.
Both probes run on the whole payload: an exact tiling can only be proven on the real datagram. Since 11.7.0 every probe does so, except the four text protocols, which keep the 18 KiB prefix (PROBE_CAP) (#185). classify_payload, given UDP and no port (None, None), reaches the strict read only, after ASTERIX.
Neither read demands a family consistent with the type. DIS_signal_and_transmitter.pcapng puts family 0 ("other") instead of 4 (radio communications) on all its radio PDUs: not conforming, but real. Family 0 is admitted, and no rule ties a family to a type.
In the corpus, the 263 frames on UDP 3000 get their label from the port rule, and 127 of the 130 on 6993 and 22999 from the blind probe; the other three need the lenient read (below). One frame of each kind, a Transmitter on port 3000 and a Signal on 6993 (tested):
#![allow(unused)] fn main() { #[test] fn a_v7_transmitter_on_udp_3000() { let raw = hex::decode(DIS_V7_TRANSMITTER_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); // UDP 3000, the customary DIS port: the port rule and its lenient read. let transport = flow.transport.as_ref().unwrap(); assert_eq!(transport.destination_port, Some(3000)); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "DIS"); // The PDU fills the datagram, so the strict read accepts it too. let packet = DisPacket::try_from(transport.payload.unwrap()).unwrap(); assert_eq!(packet.pdus.len(), 1); assert!(packet.trailing.is_empty()); let pdu = &packet.pdus[0]; assert_eq!(pdu.pdu_type, dis::PduType::Transmitter); let header = pdu.header; assert_eq!(header.protocol_version, 7); // IEEE 1278.1-2012 assert_eq!(header.exercise_id, 1); assert_eq!(header.pdu_type, 25); assert_eq!(header.protocol_family, 4); // radio communications assert_eq!(header.length, 104); assert_eq!(pdu.raw.len(), 104); assert_eq!(header.status(), Some(0)); // the PDU Status of version 7 assert!(header.absolute_timestamp()); assert_eq!(header.timestamp_units(), 1_033_452_647); // 28 min 52.46 s past the hour let DisBody::Transmitter { entity_id, radio_id, radio_entity_type, transmit_state, frequency_hz, bandwidth_hz, power_dbm, modulation_type, crypto_system, .. } = pdu.body else { panic!("expected a Transmitter body, got {:?}", pdu.body); }; assert_eq!( (entity_id.site, entity_id.application, entity_id.entity), (64128, 61467, 65534) ); assert_eq!(radio_id, 65534); assert_eq!((radio_entity_type.kind, radio_entity_type.category), (7, 1)); // radio, voice assert_eq!(transmit_state, 1); // on, not transmitting assert_eq!(frequency_hz, 100_000_000); assert_eq!(bandwidth_hz, 25_000.0); assert_eq!(power_dbm, -270.0); // Angle modulation, FM, generic radio, in tshark's words. assert_eq!( (modulation_type.major, modulation_type.detail, modulation_type.system), (3, 1, 1) ); assert_eq!(crypto_system, 0); } }
#![allow(unused)] fn main() { #[test] fn a_signal_off_port_3000_is_labelled_by_the_blind_probe() { let raw = hex::decode(DIS_V6_SIGNAL_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); // UDP 3388 -> 6993: no rule has a port for it. The blind probe labels // it, because its PDUs tile the datagram exactly. let transport = flow.transport.as_ref().unwrap(); assert_eq!( (transport.source_port, transport.destination_port), (Some(3388), Some(6993)) ); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "DIS"); let payload = transport.payload.unwrap(); let packet = DisPacket::try_from(payload).unwrap(); let pdu = &packet.pdus[0]; assert_eq!(pdu.pdu_type, dis::PduType::Signal); assert_eq!(pdu.header.protocol_version, 6); // IEEE 1278.1A-1998 assert_eq!(usize::from(pdu.header.length), payload.len()); // 1 056 bytes assert_eq!(pdu.header.status(), None); // no PDU Status before version 7 assert!(!pdu.header.absolute_timestamp()); assert_eq!(pdu.header.timestamp_units(), 89_479); // 0.15 s let DisBody::Signal { entity_id, radio_id, encoding_scheme, sample_rate, data_length, samples, data, .. } = pdu.body else { panic!("expected a Signal body, got {:?}", pdu.body); }; assert_eq!( (entity_id.site, entity_id.application, entity_id.entity), (32253, 253, 1) ); assert_eq!(radio_id, 2); assert_eq!(encoding_scheme, 0x0001); // tshark: encoded audio, 8-bit mu-law assert_eq!((sample_rate, samples), (8000, 1024)); assert_eq!(data_length, 8192); // in bits: 1 024 bytes of samples assert_eq!(data.len(), 1024); } }
The datagram and its PDUs
#![allow(unused)] fn main() { #[non_exhaustive] pub struct DisPacket<'a> { pub pdus: Vec<DisPdu<'a>>, /// Bytes after the last PDU that do not form a PDU: always empty from /// `try_from`, possibly not from `try_from_lenient`. pub trailing: &'a [u8], } #[non_exhaustive] pub struct DisPdu<'a> { pub header: DisHeader, pub pdu_type: PduType, // the named type pub body: DisBody<'a>, /// The whole PDU, header included, as its length delimits it. pub raw: &'a [u8], } }
The first PDU must decode, and its error is the error of the datagram. The next PDUs are read one after the other, each where the length of the previous one ends, until the end of the datagram or the first bytes that do not form a PDU: those bytes are trailing. try_from refuses a non-empty trailing with UnexpectedTrailingBytes, try_from_lenient keeps it. Every datagram of the corpus carries a single PDU; the path with several PDUs is checked on synthetic bytes by the crate's unit tests.
The three PDUs that need the lenient read are the Set Data, Data Query and Data of wireshark_3492_dis_test2.pcap, on UDP 6993. Here is the Set Data, refused by the blind probe and labelled once its port is declared (tested):
#![allow(unused)] fn main() { #[test] fn a_length_shorter_than_the_datagram_needs_the_lenient_read() { let raw = hex::decode(DIS_V4_SET_DATA_HEX).unwrap(); // UDP 2725 -> 6993: no port rule applies, and the strict read of the // blind probe refuses the 112 bytes after the declared 48. let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "Unknown"); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); assert_eq!(payload.len(), 160); assert_eq!( DisPacket::try_from(payload), Err(DisParseError::UnexpectedTrailingBytes { trailing: 112 }) ); // The lenient read takes the PDU its length delimits and keeps the rest. let packet = DisPacket::try_from_lenient(payload).unwrap(); assert_eq!(packet.pdus.len(), 1); let pdu = &packet.pdus[0]; assert_eq!(pdu.pdu_type, dis::PduType::SetData); assert_eq!(pdu.header.protocol_version, 4); assert_eq!(pdu.header.protocol_family, 5); // simulation management assert_eq!(pdu.header.length, 48); assert!(matches!(pdu.body, DisBody::Opaque(body) if body.len() == 36)); assert_eq!(packet.trailing.len(), 112); // Declaring the port selects the lenient read, as port 3000 does. let config = ParseConfig::new().decode_as(6993, DecodeAsProtocol::Dis); let flow = parse_with(LinkType::ETHERNET, &raw, &config).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "DIS"); } }
The header: DisHeader
#![allow(unused)] fn main() { #[non_exhaustive] pub struct DisHeader { pub protocol_version: u8, pub exercise_id: u8, pub pdu_type: u8, // the raw code; DisPdu::pdu_type names it pub protocol_family: u8, /// Raw: 31 bits of time in units of 1/2^31 hour, and the low bit set /// for an absolute time. pub timestamp: u32, /// Declared length of the PDU, header included. pub length: u16, /// PDU Status in version 7; padding before. pub pdu_status: u8, pub padding: u8, } }
| Bytes | Field | Note |
|---|---|---|
| 0 | protocol_version | 1 to 7, from DIS PDU version 1.0 to IEEE 1278.1-2012 |
| 1 | exercise_id | |
| 2 | pdu_type | 1 to 72 |
| 3 | protocol_family | 0 to 13 from the standard, or 129 to 255, experimental |
| 4–7 | timestamp | read with absolute_timestamp() and timestamp_units() |
| 8–9 | length | at least 12, at most the bytes left in the datagram |
| 10 | pdu_status | status() is Some from version 7 on, None before |
| 11 | padding |
Version 7, IEEE 1278.1-2012, is the first with a PDU Status field. absolute_timestamp() reads the low bit of timestamp, and timestamp_units() returns the other 31 bits, a count of 1/2^31 hour, so always less than an hour: 1 033 452 647 on the Transmitter above, 28 min 52.46 s, which is what tshark prints. The crate converts nothing further.
PduType names the 72 types of SISO-REF-010 in the order of their codes, from 1 EntityState, 2 Fire and 3 Detonation to 72 Attribute; the corpus has 18 DataQuery, 19 SetData, 20 Data, 25 Transmitter, 26 Signal and 29 UnderwaterAcoustic. The header keeps the raw code, DisPdu::pdu_type the name.
Three typed bodies
#![allow(unused)] fn main() { #[non_exhaustive] pub enum DisBody<'a> { /// Entity State (§7.2.2): the position and appearance of an entity. EntityState { entity_id: EntityId, force_id: u8, /// Number of articulation or attachment parameters that follow. variable_parameter_count: u8, entity_type: EntityType, alternative_entity_type: EntityType, linear_velocity: Vector3, // meters per second location: WorldCoordinates, orientation: Vector3, // Euler angles psi, theta, phi, radians appearance: u32, /// Dead reckoning algorithm, the first byte of its parameters. dead_reckoning_algorithm: u8, /// Character set, then eleven bytes of marking. marking: [u8; 12], capabilities: u32, /// The variable parameters, sixteen bytes each. variable_parameters: &'a [u8], }, /// Transmitter (§7.7.2): the state of a simulated radio transmitter. Transmitter { entity_id: EntityId, radio_id: u16, radio_entity_type: EntityType, transmit_state: u8, // 0 off, 1 on but not transmitting, 2 transmitting input_source: u8, /// Version 7: number of variable transmitter parameters; padding before. variable_parameter_count: u16, antenna_location: WorldCoordinates, relative_antenna_location: Vector3, antenna_pattern_type: u16, antenna_pattern_length: u16, frequency_hz: u64, bandwidth_hz: f32, power_dbm: f32, // decibel-milliwatts modulation_type: ModulationType, crypto_system: u16, crypto_key_id: u16, modulation_parameter_length: u8, }, /// Signal (§7.7.3): audio samples or radio data. Signal { entity_id: EntityId, radio_id: u16, encoding_scheme: u16, tdl_type: u16, sample_rate: u32, data_length: u16, // in bits samples: u16, /// The data, final padding included. data: &'a [u8], }, /// Any other type: the raw body, header excluded. Opaque(&'a [u8]), } }
The records inside the bodies are small #[non_exhaustive] structs, read but never built outside the crate:
#![allow(unused)] fn main() { pub struct EntityId { pub site: u16, pub application: u16, pub entity: u16 } pub struct EntityType { // the seven fields of the SISO enumeration pub kind: u8, pub domain: u8, pub country: u16, pub category: u8, pub subcategory: u8, pub specific: u8, pub extra: u8, } pub struct ModulationType { /// Bits: 0 frequency hopping, 1 pseudo-noise, 2 time hopping. pub spread_spectrum: u16, pub major: u16, pub detail: u16, pub system: u16, } pub struct Vector3 { pub x: f32, pub y: f32, pub z: f32 } pub struct WorldCoordinates { pub x: f64, pub y: f64, pub z: f64 } // geocentric, meters }
All values are big-endian. The offsets below count from the start of the PDU, header included, so the body starts at byte 12.
Entity State (type 1):
| Bytes | Field | Note |
|---|---|---|
| 12–17 | entity_id | EntityId |
| 18 | force_id | |
| 19 | variable_parameter_count | records from byte 144 on |
| 20–27 | entity_type | EntityType |
| 28–35 | alternative_entity_type | EntityType |
| 36–47 | linear_velocity | Vector3 |
| 48–71 | location | WorldCoordinates |
| 72–83 | orientation | Vector3 |
| 84–87 | appearance | raw bits |
| 88 | dead_reckoning_algorithm | the first of the 40 bytes of dead-reckoning parameters (88–127); the other 39 are not exposed |
| 128–139 | marking | character set, then 11 characters |
| 140–143 | capabilities | raw bits |
| 144– | variable_parameters | 16 bytes per record, raw |
Transmitter (type 25):
| Bytes | Field | Note |
|---|---|---|
| 12–17 | entity_id | EntityId |
| 18–19 | radio_id | |
| 20–27 | radio_entity_type | EntityType |
| 28 | transmit_state | |
| 29 | input_source | |
| 30–31 | variable_parameter_count | version 7; padding before |
| 32–55 | antenna_location | WorldCoordinates |
| 56–67 | relative_antenna_location | Vector3 |
| 68–69 | antenna_pattern_type | |
| 70–71 | antenna_pattern_length | |
| 72–79 | frequency_hz | |
| 80–83 | bandwidth_hz | f32 |
| 84–87 | power_dbm | f32 |
| 88–95 | modulation_type | ModulationType |
| 96–97 | crypto_system | |
| 98–99 | crypto_key_id | |
| 100 | modulation_parameter_length | |
| 101–103 | padding | not exposed |
Signal (type 26):
| Bytes | Field | Note |
|---|---|---|
| 12–17 | entity_id | EntityId |
| 18–19 | radio_id | |
| 20–21 | encoding_scheme | raw: 0x0001 on the Signal above, encoded audio, 8-bit mu-law for tshark |
| 22–23 | tdl_type | |
| 24–27 | sample_rate | |
| 28–29 | data_length | in bits |
| 30–31 | samples | |
| 32– | data | to the end of the PDU |
A body must hold the fixed fields of its type, or the PDU is BodyTooShort { pdu_type, expected, actual }: 132 bytes for an Entity State plus 16 per announced variable parameter (a PDU of 144 + 16 n bytes), 92 for a Transmitter (a PDU of 104), 20 for a Signal (a PDU of 32). A longer body is accepted, and what the decoder does not read stays in raw. After the 92 fixed bytes of a Transmitter come its modulation parameters, its antenna pattern and, in version 7, the variable transmitter parameter records that variable_parameter_count announces; none of them are decoded. The 120-byte Transmitters of dis_voice_sample.pcap carry 16 bytes of modulation parameters. The 149-byte Transmitters of DIS_signal_and_transmitter.pcapng, in version 5, announce no modulation parameters and no antenna pattern, and still run 45 bytes past the fixed fields; they decode all the same.
The corpus has no Entity State: the wiki captures that carry some were set aside as replayed PDUs rather than recorded exercises (see the SOURCE.md of the corpus folder), so this body is checked on synthetic bytes only, by a unit test of the crate.
Validations
All of them are DisParseError, in packet_parser::errors::application::dis:
| Error | When |
|---|---|
Truncated { expected, actual } | fewer than the 12 bytes of a header |
UnsupportedVersion(u8) | a version other than 1 to 7 |
ReservedPduType(u8) | a type other than 1 to 72 |
ReservedProtocolFamily(u8) | a family from 14 to 128 |
InvalidLength(u16) | a declared length shorter than the header |
LengthOverflow { declared, available } | a declared length beyond the bytes left in the datagram |
UnexpectedTrailingBytes { trailing } | try_from only: bytes after the last PDU that do not form a PDU |
BodyTooShort { pdu_type, expected, actual } | an Entity State, Transmitter or Signal body shorter than its fixed fields, plus 16 bytes per announced variable parameter for an Entity State |
Only the first PDU reports its own error. After it, a PDU that fails ends the list, and from try_from the datagram is then refused with UnexpectedTrailingBytes. Like every application decoder, a failure only means no label: the dispatch moves on to the next rule, and nothing goes to corrupted.
Oracle: 393 frames, frame by frame
The golden test tests/dis_golden.rs runs the five captures of pcaps_exemple/protocols/dis/ and compares every frame with tshark 4.6.6, frozen in tests/data/dis_tshark_oracle.tsv by tools/dis_oracle.sh with DIS decoding forced on UDP 3000, 6993 and 22999: version, exercise, type, family, length, PDU Status and the first entity identifier of the body. The crate is queried the way tshark is, ports 6993 and 22999 declared by Decode As, and all 393 frames are labelled "DIS" and match. Without the declarations, 390 are labelled "DIS"; the three PDUs of wireshark_3492_dis_test2.pcap stay "Unknown". By type, 302 Signal, 72 Transmitter, 16 Underwater Acoustic and one each of Data Query, Set Data and Data; by version, 3 in version 4, 269 in version 5, 111 in version 6 and 10 in version 7.
| Capture | Frames | Version, PDUs | Port | Origin |
|---|---|---|---|---|
dis_voice_sample.pcap | 111 | v6, Signal and Transmitter | UDP 6993 | Wireshark test/captures |
DIS_signal_and_transmitter.pcapng | 253 | v5, Signal and Transmitter, family 0 | UDP 3000 | Wireshark wiki |
wireshark_8185_dis_ua.pcapng | 16 | v5, Underwater Acoustic | UDP 22999 | Wireshark issue 8185 |
wireshark_12043_dis_v7_transmitter.pcap | 10 | v7, Transmitter | UDP 3000 | Wireshark issue 12043 |
wireshark_3492_dis_test2.pcap | 3 | v4, Data Query, Set Data, Data | UDP 6993 | Wireshark issue 3492 |
In the golden histogram of the whole corpus, "DIS" went from 0 to 390 with 11.6.0, all taken from "Unknown". The fuzz target parse_dis runs nightly on both reads: no panic, and when a decode succeeds, the PDUs and trailing tile the input exactly and the strict read accepts nothing the lenient one refuses.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- 69 of the 72 types keep their body raw, in
DisBody::Opaque: Fire, Detonation, Underwater Acoustic, the simulation management PDUs... - Inside the typed bodies: the dead-reckoning parameters after the algorithm byte, the variable parameters (raw 16-byte records), the modulation parameters, antenna pattern and variable transmitter parameters of a Transmitter, and the data of a Signal (no audio, no tactical data link message) are not decoded.
appearanceandcapabilitiesare raw bits. - Enumerations are numbers: entity kinds, countries, modulations and encodings are the values of SISO-REF-010, not names.
- No state: no dead reckoning, no pairing of a Signal with its Transmitter, no time conversion. One datagram at a time, like the rest of the crate.
DNP3
DNP3, the Distributed Network Protocol of IEEE 1815, is the SCADA protocol of the North American electric sector, spoken between a master and its outstations. It was added in 11.6.0 (#99), and its European counterpart, IEC 60870-5-104, came in the same release. The module is packet_parser::parse::application::protocols::dnp3, the errors are in packet_parser::errors::application::dnp3, and the label is "DNP3".
A DNP3 message has three layers, and the crate reads all three, one payload at a time and without state: the link frame, protected by CRCs; the transport header, one byte per frame that marks the pieces of an application fragment spread over several frames; and the application layer, a header and a chain of object headers.
Detection: the CRC is the signature
DNP3 runs on TCP or UDP, usually on port 20000, and the crate looks at neither the port nor the transport: the rule is a blind probe without a transport guard, rule(ApplicationProtocol::Dnp3, Guard::Any, ProbeId::Dnp3), rule 51 of the table, in the blind cascade after DIS and before RADIUS. Port 20000 appears in no rule. What makes a blind probe safe here is the link layer itself: every frame starts with 05 64, and its header and each block of sixteen bytes of user data carry a CRC-16/DNP that the decoder checks. A payload that is not DNP3 has to get every one of those CRCs right.
The probe is Dnp3Packet::try_from on the whole payload, as every probe but the four text ones since 11.7.0: the link frames, each checked by its CRCs, must tile the segment or the datagram to the last byte. There is no DecodeAsProtocol variant for DNP3: Decode As extends port guards, and this rule has none. classify_payload reads the same table: with no port (None, None) it tries DNP3 under either transport.
The corpus shows both directions of the rule. dnp3_read_p20001.pcap is dnp3_read.pcap with its port rewritten to 20001: tshark 4.6.6 shows its two segments with a payload as data until its DNP3 dissector is forced on that port (-d tcp.port==20001,dnp3, as the oracle does), while the crate labels them "DNP3" like any other. And on port 20000 itself, two segments of dnp3.pcap (frames 19 and 21) start with 05 05: tshark shows them as data, the crate as "Unknown".
The read request of dnp3_read.pcap on a port no rule knows, then a read of the same four classes over UDP (tested):
#![allow(unused)] fn main() { #[test] fn dnp3_is_recognized_by_its_crcs_on_any_port_tcp_or_udp() { // Frame 4 of dnp3_read_p20001.pcap: TCP 51006 -> 20001. No rule of // the table knows that port: the label comes from the content. let raw = hex::decode(DNP3_TCP_READ_REQUEST_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let transport = flow.transport.as_ref().unwrap(); assert_eq!(transport.destination_port, Some(20001)); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "DNP3"); let packet = Dnp3Packet::try_from(transport.payload.unwrap()).unwrap(); let [frame] = &packet.frames[..] else { panic!("expected one link frame"); }; // Link layer: LENGTH 20, control 0xC4, from master 3 to outstation 2. let link = frame.header; assert_eq!((link.length, link.control), (20, 0xc4)); assert!(link.direction_from_master() && link.primary()); assert_eq!(link.function(), Some(LinkFunction::UnconfirmedUserData)); assert_eq!((link.destination, link.source), (2, 3)); assert_eq!(link.crc, 0x0345); // 27 bytes on the wire, 15 of user data once the two CRCs are removed. assert_eq!((frame.raw.len(), frame.user_data.len()), (27, 15)); // Transport: a single segment, first and last of its fragment. let segment = frame.transport.unwrap(); assert!(segment.is_first() && segment.is_final()); assert_eq!(segment.sequence(), 7); // Application: a Read of the four class objects, without range or data. let application = frame.application.as_ref().unwrap(); assert_eq!(application.header.function(), Some(ApplicationFunction::Read)); assert_eq!(application.header.sequence(), 8); assert_eq!(application.header.internal_indications, None); let objects: Vec<(u8, u8, u8)> = application .objects .iter() .map(|object| (object.group, object.variation, object.qualifier)) .collect(); assert_eq!(objects, [(60, 2, 0x06), (60, 3, 0x06), (60, 4, 0x06), (60, 1, 0x06)]); assert!(application.objects.iter().all(|object| object.range == RangeSpecifier::All)); assert!(application.objects.iter().all(|object| object.data.is_empty())); assert!(application.undecoded.is_empty()); // Frame 5 of dnp3_udp_read.pcap: a read of the same four classes, over // UDP 1128 -> 20000, labelled by the same rule. let raw = hex::decode(DNP3_UDP_READ_REQUEST_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let transport = flow.transport.as_ref().unwrap(); assert_eq!(transport.protocol, TransportProtocol::Udp); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "DNP3"); let udp = Dnp3Packet::try_from(transport.payload.unwrap()).unwrap(); let udp_read = udp.frames[0].application.as_ref().unwrap(); assert_eq!(udp_read.header.function(), Some(ApplicationFunction::Read)); assert_eq!(udp_read.objects, application.objects); } }
The link frame
#![allow(unused)] fn main() { pub struct Dnp3Packet<'a> { pub frames: Vec<LinkFrame<'a>>, // one or more, tiling the payload } pub struct LinkFrame<'a> { pub header: LinkHeader, pub raw: &'a [u8], // the frame as on the wire, CRCs included pub user_data: Vec<u8>, // CRCs removed: at most 250 bytes pub transport: Option<TransportHeader>, // None without user data pub application: Option<ApplicationFragment>, // first segment of a fragment only } pub struct LinkHeader { pub length: u8, // the bytes after LENGTH, CRCs excluded: 5 plus the user data pub control: u8, // raw: DIR, PRM, FCB, FCV, function code pub destination: u16, pub source: u16, pub crc: u16, // as transmitted, checked by the decoder } }
Like every public type of the module, they are #[non_exhaustive]. The 10-byte header (IEEE 1815-2012 §9.2.4):
| Bytes | Field | Note |
|---|---|---|
| 0–1 | start | 05 64, otherwise InvalidStartBytes |
| 2 | length | control, destination and source (5), plus the user data, CRCs not counted: below 5 is InvalidLength, and 255 allows 250 bytes of user data |
| 3 | control | DIR 0x80 direction_from_master(), PRM 0x40 primary(), FCB 0x20 frame_count_bit(), FCV 0x10 frame_count_valid() (DFC in a secondary frame), function code in the low nibble, function_code() |
| 4–5 | destination | little-endian |
| 6–7 | source | little-endian |
| 8–9 | crc | CRC of bytes 0 to 7, little-endian; a mismatch is HeaderCrcMismatch { expected, actual } |
| 10… | user data | blocks of 16 bytes, the last one possibly shorter, each followed by its own CRC; a mismatch is BlockCrcMismatch { block, expected, actual }, block counted from 0 |
A frame with n bytes of user data is 10 + n + 2 × ⌈n / 16⌉ bytes long on the wire: 27 bytes for the 15 bytes of a read request, 292 for a full frame of 250. A buffer shorter than the 10-byte header, or than the frame its length announces, is Truncated { expected, actual }. The CRC is CRC-16/DNP (§9.2.4.3 and annex E): polynomial 0x3D65, reflected, complemented, transmitted least significant byte first; its implementation is internal to the crate.
function() names the code according to PRM, as LinkFunction:
| PRM | Code | LinkFunction |
|---|---|---|
| 1 (primary) | 0, 2, 3, 4, 9 | ResetLinkStates, TestLinkStates, ConfirmedUserData, UnconfirmedUserData, RequestLinkStatus |
| 0 (secondary) | 0, 1, 11, 15 | Ack, Nack, LinkStatus, NotSupported |
Any other combination is None, which does not fail the decode.
user_data is the only part of the payload the decoder copies: the CRCs interrupt the data every sixteen bytes, so a slice of the payload would not be contiguous. raw still borrows the frame as received.
Dnp3Packet::try_from reads frames back to back until the payload is consumed, and every one of them must be complete and valid. Bytes left after the last frame are read as the start of another frame and fail like one, as Truncated or InvalidStartBytes for instance: UnexpectedTrailingBytes is declared but never returned. In the corpus, every segment and datagram holds exactly one frame.
The transport header
#![allow(unused)] fn main() { pub struct TransportHeader { pub raw: u8, // FIN 0x80, FIR 0x40, sequence on six bits } }
It is the first byte of the user data: is_final() (FIN), is_first() (FIR) and sequence(). A frame without user data, a link function such as RequestLinkStatus, has transport: None and no application.
An application fragment longer than one frame can carry is cut into transport segments, one per frame, from a FIR segment to a FIN segment. The decoder reads the application header and the object headers on the FIR segment only, as far as that frame goes; the following segments get their link and transport headers and application: None. Nothing is reassembled: tshark does reassemble, and shows the application layer on the last segment of the fragment. In dnp3_udp_read.pcap, the first fragment of a response spans frames 6 to 14, transport sequence 32 to 40: on frame 6 the crate reads the application header that tshark shows on frame 14, control 0x87, a Response, IIN 90 00, and the first two of the three object headers tshark lists, g1v1 and g10v2.
The application header has its own FIR bit, which marks the first fragment of a message made of several: control 0x87 is FIR without FIN, and frames 15 to 21 carry the second and last fragment of that response, whose control on frame 15 is 0x48, FIN without FIR. dnp3_link_only.pcap has the same shape: its frame 22 is a transport FIR segment whose application control is 0x48, the second and last fragment of the response that frame 9 began.
A link frame without data, then the first two segments of the dnp3_udp_read.pcap response (tested):
#![allow(unused)] fn main() { #[test] fn dnp3_link_only_frames_and_fragments_over_several_frames() { // Frame 1 of dnp3_link_only.pcap: a link function, LENGTH 5, no user // data, hence no transport header and no application. let raw = hex::decode(DNP3_REQUEST_LINK_STATUS_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = Dnp3Packet::try_from(payload).unwrap(); let status = &packet.frames[0]; assert_eq!(status.header.function(), Some(LinkFunction::RequestLinkStatus)); assert!(status.user_data.is_empty()); assert!(status.transport.is_none() && status.application.is_none()); // Frame 6 of dnp3_udp_read.pcap: a full link frame (LENGTH 255, 250 // bytes of user data), first of the nine segments of the first // fragment of a response. let raw = hex::decode(DNP3_UDP_FIRST_SEGMENT_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = Dnp3Packet::try_from(payload).unwrap(); let first = &packet.frames[0]; assert_eq!((payload.len(), first.user_data.len()), (292, 250)); let segment = first.transport.unwrap(); assert!(segment.is_first() && !segment.is_final()); assert_eq!(segment.sequence(), 32); // FIR: the application fragment starts here, and its header is read. let application = first.application.as_ref().unwrap(); assert_eq!(application.header.control, 0x87); // FIR, not FIN: fragment 1 of 2 assert_eq!(application.header.function(), Some(ApplicationFunction::Response)); assert_eq!(application.header.internal_indications, Some([0x90, 0x00])); // 1 024 packed binary inputs fit in 128 bytes; the next header is // read, but its 512 bytes of data go beyond the frame: the chain stops. let [inputs, outputs] = &application.objects[..] else { panic!("expected two object headers"); }; assert_eq!((inputs.group, inputs.variation, inputs.data.len()), (1, 1, 128)); assert_eq!((outputs.group, outputs.variation), (10, 2)); assert_eq!(outputs.range.object_count(), Some(512)); assert!(outputs.data.is_empty()); assert_eq!(application.undecoded, 147..250); // Frame 7, the next segment of the same fragment: not FIR, so link // and transport only. The stateless parser does not reassemble. let raw = hex::decode(DNP3_UDP_NEXT_SEGMENT_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = Dnp3Packet::try_from(payload).unwrap(); let next = &packet.frames[0]; let segment = next.transport.unwrap(); assert!(!segment.is_first() && !segment.is_final()); assert_eq!(segment.sequence(), 33); assert!(next.application.is_none()); } }
The application layer
#![allow(unused)] fn main() { pub struct ApplicationFragment { pub header: ApplicationHeader, pub objects: Vec<ObjectHeader>, pub undecoded: Range<usize>, // in user_data; empty when everything was read } pub struct ApplicationHeader { pub control: u8, // raw: FIR 0x80, FIN 0x40, CON 0x20, UNS 0x10, sequence on four bits pub function_code: u8, pub internal_indications: Option<[u8; 2]>, // IIN1 then IIN2, responses only } }
The control byte has its accessors, is_first(), is_final(), confirm_requested(), unsolicited() and sequence(). A response, function 0x81 Response, 0x82 UnsolicitedResponse or 0x83 AuthenticationResponse (is_response()), adds the two bytes of internal indications. function() names the code as one of the 37 variants of ApplicationFunction, codes 0 to 33 and 0x81 to 0x83; an unknown code is None and the decode goes on. A FIR segment whose application header is shorter than 2 bytes, 4 for a response, is ApplicationHeaderTooShort { actual }.
Then come the object headers, one after the other to the end of the user data:
#![allow(unused)] fn main() { pub struct ObjectHeader { pub group: u8, pub variation: u8, pub qualifier: u8, // raw pub prefix: PrefixCode, pub range: RangeSpecifier, pub data: Range<usize>, // the objects, prefixes included, in user_data } pub enum PrefixCode { None, Index { octets: u8 }, // each object preceded by its index, 1, 2 or 4 bytes Size { octets: u8 }, // each object preceded by its size, 1, 2 or 4 bytes Reserved(u8), } pub enum RangeSpecifier { StartStop { start: u32, stop: u32, octets: u8 }, // codes 0 to 2 Absolute { start: u32, stop: u32, octets: u8 }, // codes 3 to 5 All, // code 6: no range field, no data Count { count: u32, octets: u8 }, // codes 7 to 9 VariableCount { count: u8 }, // code 11 Reserved(u8), // codes 10, 12 to 15 } }
The qualifier is two codes (§4.2.2.7.1).
- Its low nibble is the range code. The range fields that follow the header are 1, 2 or 4 bytes wide according to it.
- Bits 4 to 6 are the prefix code: 1 to 3 an index, 4 to 6 a size, each on 1, 2 or 4 bytes; 7 is reserved.
- Bit 7 of the qualifier is reserved too, and is not read.
range.object_count() gives the number of objects the range announces: stop − start + 1, or the count.
| Range | object_count() | In 11.6.0 |
|---|---|---|
All, Reserved | None | the same |
| inverted: the stop precedes the start by more than one index (#181) | None | the same |
full: 0 to 0xFFFFFFFF on four bytes, range codes 2 and 5 (#180) | None: its 232 objects do not fit in a u32 | an overflow |
| empty: a stop one index below the start, 5 to 4 | Some(0) | None |
The overflow of 11.6.0 was a panic with overflow checks (debug builds, cargo fuzz), and Some(0) in release. The probe being blind, a 28-byte frame with valid CRCs, in any TCP segment or almost any UDP datagram, was enough to make parse() panic.
Whether data follows a header depends on the function.
Some functions carry headers only: Confirm, Read, the immediate freezes and freeze-and-clears (codes 7 to 10), the cold and warm restarts, enable and disable unsolicited, assign class, delay measurement and record current time. There are two exceptions:
- Objects prefixed by their size carry their data. A file block read (g70v5, qualifier
0x5b) carries the file handle and the block number. - A header prefixed by indexes, qualifier
0x17,0x28or0x39for instance, carries the list of the points the request asks for, without objects. Since 11.7.0 (#182),datacovers that list, the count times the width of an index, and the chain goes on after it. 11.6.0 did not step over the list: it read the indexes as the next header, and invented headers.
For the other functions, the size of the objects comes from a table of IEEE 1815-2012 annex A in the crate. It gives one of three things:
- a fixed size in bytes;
- packed bits: one bit per point for g1v1, g10v1, g12v3 and g80v1, among them the binary inputs, binary outputs and internal indications, and two bits for g3v1;
- a size carried by the prefix, for files, device profiles, data sets and authentication among others.
data is then the range of the objects in user_data, and LinkFrame::object_data(&header) the bytes.
The chain stops at a header whose prefix or range code is reserved, at an inverted range, and at a header whose objects, sizes or indexes cannot be delimited: when the function carries data, a group and variation the table does not know or a variable-size object without a size prefix, and data or an index list that goes beyond the frame. That header is still listed, with an empty data, and what follows it is undecoded; a header cut before its last range field is not listed at all. A header that announces no object, an empty range or a zero count, never stops the chain, whatever its group, unless its prefix code is reserved, which is tested first. Both rules changed in 11.7.0 (#181): 11.6.0 treated an inverted range like All and read what followed it as a new header, and it stopped on the zero count of an unknown group or of objects it could not delimit.
On the full range, the decoder counts the 232 objects on 64 bits, and the size of their data, computed on 64 bits too, decides what follows (#180). When nothing follows the header, in a read without prefix, or for objects of size zero such as class 0 (g60v1) in a response, the chain goes on. When objects, sizes or indexes must follow, they fit in no frame, and the chain stops on that header. On a 32-bit target, an object prefixed by a 4-byte size close to 0xFFFFFFFF made the computation of the position of the next size overflow in 11.6.0, another panic with overflow checks that parse() could reach; since 11.7.0 that computation is checked, and the chain stops on that header, as it did in release builds.
Synthetic frames, most of them from the crate's unit tests: a read and a response over the full range (tested):
#![allow(unused)] fn main() { #[test] fn dnp3_the_full_range_has_no_u32_count() { // A read of g30v1 over the full range, then of class 0. let bytes = hex::decode(DNP3_FULL_RANGE_READ_HEX).unwrap(); let packet = Dnp3Packet::try_from(bytes.as_slice()).unwrap(); let read = packet.frames[0].application.as_ref().unwrap(); assert_eq!(read.header.function(), Some(ApplicationFunction::Read)); let [analogs, class_0] = &read.objects[..] else { panic!("expected two object headers"); }; assert_eq!( analogs.range, RangeSpecifier::StartStop { start: 0, stop: u32::MAX, octets: 4 } ); // 2^32 objects do not fit in a u32: no count, and no overflow. assert_eq!(analogs.range.object_count(), None); // A read carries no objects: nothing follows the header, and the chain // goes on to the class 0 header. assert!(analogs.data.is_empty()); assert_eq!((class_0.group, class_0.variation), (60, 1)); assert!(read.undecoded.is_empty()); // One object fewer, and the count is a u32 again. let bytes = hex::decode(DNP3_ALMOST_FULL_RANGE_READ_HEX).unwrap(); let packet = Dnp3Packet::try_from(bytes.as_slice()).unwrap(); let read = packet.frames[0].application.as_ref().unwrap(); assert_eq!(read.objects[0].range.object_count(), Some(u32::MAX)); assert_eq!(read.objects.len(), 2); // The full range in a response: 2^32 analog inputs of five bytes fit in // no frame. The chain stops on that header, which is still listed, and // the class 0 header after it stays undecoded. let bytes = hex::decode(DNP3_FULL_RANGE_RESPONSE_HEX).unwrap(); let packet = Dnp3Packet::try_from(bytes.as_slice()).unwrap(); let frame = &packet.frames[0]; let response = frame.application.as_ref().unwrap(); assert_eq!(response.header.function(), Some(ApplicationFunction::Response)); let [analogs] = &response.objects[..] else { panic!("expected one object header"); }; assert_eq!(analogs.range.object_count(), None); assert!(analogs.data.is_empty()); assert_eq!(frame.user_data[response.undecoded.clone()], [60, 1, 0x06]); } }
A read of two points by index, then an empty and an inverted range (tested):
#![allow(unused)] fn main() { #[test] fn dnp3_requested_points_and_inverted_ranges() { // A read of points 3 and 7 by index: a one-byte count, then each point // as its one-byte index, without objects. let bytes = hex::decode(DNP3_READ_BY_INDEX_HEX).unwrap(); let packet = Dnp3Packet::try_from(bytes.as_slice()).unwrap(); let frame = &packet.frames[0]; let read = frame.application.as_ref().unwrap(); let [points, class_0] = &read.objects[..] else { panic!("expected two object headers"); }; assert_eq!(points.qualifier, 0x17); assert_eq!(points.prefix, PrefixCode::Index { octets: 1 }); assert_eq!(points.range, RangeSpecifier::Count { count: 2, octets: 1 }); // `data` is the list of the indexes, and the chain goes on after it. assert_eq!(frame.object_data(points), [3, 7]); assert_eq!((class_0.group, class_0.variation), (60, 1)); assert!(read.undecoded.is_empty()); // From 5 to 4, the range is empty: zero objects, and the chain goes on. let bytes = hex::decode(DNP3_EMPTY_RANGE_READ_HEX).unwrap(); let packet = Dnp3Packet::try_from(bytes.as_slice()).unwrap(); let read = packet.frames[0].application.as_ref().unwrap(); assert_eq!(read.objects[0].range.object_count(), Some(0)); assert_eq!(read.objects.len(), 2); // From 5 to 2, the range is inverted: no count, and the chain stops. let bytes = hex::decode(DNP3_INVERTED_RANGE_READ_HEX).unwrap(); let packet = Dnp3Packet::try_from(bytes.as_slice()).unwrap(); let frame = &packet.frames[0]; let read = frame.application.as_ref().unwrap(); let [inverted] = &read.objects[..] else { panic!("expected one object header"); }; assert_eq!(inverted.range, RangeSpecifier::StartStop { start: 5, stop: 2, octets: 1 }); assert_eq!(inverted.range.object_count(), None); assert_eq!(frame.user_data[read.undecoded.clone()], [60, 1, 0x06]); } }
tshark 4.6.6 stops at the same places on missing data, on an unknown group that announces objects, and on a negative count ("Negative number of items"). They differ in the cases below, which the comments of the decoder describe and, for most of them, its unit tests freeze on synthetic frames:
- The full range, range code 2. tshark computes the count on 32 bits, where 232 wraps to zero, and reads the next header where the crate stops, when objects, sizes or indexes must follow the full range.
- Inverted ranges on four bytes. From 10 to 5, tshark's count is −4, and it stops like the crate. When the start exceeds the stop by more than 231 + 1, from
0xFFFFFFFFto 5, its 32-bit count is positive again, and it goes on where the crate stops. The other way round, a range of 231 to 232 − 1 objects, such as 0 to0xFFFFFFFE, has a negative count for tshark, which stops, while the crate goes on when nothing follows the header. - Range codes 3 to 5. tshark reads them as a single address, one object, and the bytes after it as a new header; the crate reads a start and a stop, counts them like codes 0 to 2, and stops on an inverted address range. The comparisons above hold for range code 2 only.
- Index lists. In a read or a freeze of a precise variation (g30v1, g20v1...), tshark steps over the indexes, like the crate. For a default variation or a class (g1v0, g20v0, g60v1...), it steps over the first index only and reads the next ones as a header, and it decodes no object of an Assign Class.
- Reserved range and prefix codes. After a reserved range code, tshark reads zero objects and the next header; after a reserved prefix code, it reads the objects without a prefix, then the next header. The crate stops on both.
Frames 154 and 156 of dnp3.pcap show a real case: a Disable Unsolicited whose third header, g60v4, has the qualifier byte 0xed, prefix code 6 and range code 13 once bit 7 is set aside. Range code 13 is not defined by the standard: the crate lists the header with PrefixCode::Size { octets: 4 } and RangeSpecifier::Reserved(13) and would read nothing past it (nothing follows it here), and tshark shows an "Unknown Range Type".
The values themselves are not decoded: the crate says where each object is, the caller reads it. A response with three object headers (tested):
#![allow(unused)] fn main() { #[test] fn dnp3_object_headers_locate_the_data_the_caller_reads() { // Frame 6 of dnp3_read.pcap: the outstation answers the read. let raw = hex::decode(DNP3_TCP_RESPONSE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = Dnp3Packet::try_from(payload).unwrap(); let frame = &packet.frames[0]; // 111 bytes of user data in seven blocks (6 x 16 + 15), each followed // by its CRC: 10 + 111 + 7 x 2 = 135 bytes on the wire. assert_eq!(frame.header.length, 116); assert_eq!((payload.len(), frame.user_data.len()), (135, 111)); assert!(!frame.header.direction_from_master()); let application = frame.application.as_ref().unwrap(); assert_eq!(application.header.function(), Some(ApplicationFunction::Response)); assert_eq!(application.header.internal_indications, Some([0x00, 0x00])); // Three headers, qualifier 0x00: no prefix, start and stop on one byte. let [inputs, outputs, analogs] = &application.objects[..] else { panic!("expected three object headers"); }; assert_eq!((inputs.group, inputs.variation), (1, 2)); // binary inputs with flags assert_eq!((outputs.group, outputs.variation), (10, 2)); // binary output status assert_eq!((analogs.group, analogs.variation), (30, 1)); // 32-bit analog inputs assert!(application.objects.iter().all(|object| object.prefix == PrefixCode::None)); assert_eq!( analogs.range, RangeSpecifier::StartStop { start: 0, stop: 14, octets: 1 } ); assert_eq!(analogs.range.object_count(), Some(15)); // Where the objects are in `user_data`. Their size comes from the table // of annex A: one byte per point for the first two, five (a flag and // an i32) for the analogs, 15 x 5 = 75 bytes. assert_eq!(inputs.data, 10..19); assert_eq!(outputs.data, 24..31); assert_eq!(analogs.data, 36..111); assert!(application.undecoded.is_empty()); // The crate locates the objects; reading the values is the caller's job. let points = frame.object_data(analogs); let point = |index: usize| { let bytes = &points[index * 5..index * 5 + 5]; (bytes[0], i32::from_le_bytes([bytes[1], bytes[2], bytes[3], bytes[4]])) }; assert_eq!(point(0), (0x01, 1007)); // flag ONLINE, value 1007, as tshark shows assert_eq!(point(3), (0x01, -11989)); } }
Validations
All of them are Dnp3ParseError:
| Error | When |
|---|---|
Truncated { expected, actual } | fewer than the 10 bytes of a link header, or than the frame its length announces |
InvalidStartBytes([u8; 2]) | a frame that does not start with 05 64 |
InvalidLength(u8) | length below 5 |
HeaderCrcMismatch { expected, actual } | the CRC of the 8 header bytes does not match |
BlockCrcMismatch { block, expected, actual } | the CRC of a block of user data does not match |
ApplicationHeaderTooShort { actual } | a FIR segment with less than 2 bytes of application header, 4 for a response |
UnexpectedTrailingBytes { trailing } | declared, never returned (see above) |
The object headers never fail the decode, and 11.7.0 adds no error: a header the decoder cannot get past is listed, and the rest of the fragment is undecoded. What each kind of header gives:
| Object header | range.object_count() | Object chain |
|---|---|---|
range code 6, All | None | goes on |
| reserved prefix or range code | None for a reserved range code | stops |
| empty range (5 to 4) or zero count | Some(0); None for 5 to 4 in 11.6.0 | goes on, whatever the group (11.7.0) |
| inverted range (5 to 2) | None | stops (11.7.0; 11.6.0 went on) |
full range, 0 to 0xFFFFFFFF (codes 2 and 5) | None (11.7.0; overflow in 11.6.0) | goes on when nothing follows the header, stops otherwise |
| index prefix in a request without object data | the count | goes on after the index list (11.7.0); stops when the list goes beyond the frame |
| objects that cannot be delimited, or data beyond the frame | the count | stops |
A refused payload is not labelled DNP3: it goes on to the next rules of the table and usually comes out "Unknown", with nothing in corrupted, since no layer announced DNP3. One altered bit is enough (tested):
#![allow(unused)] fn main() { #[test] fn dnp3_one_altered_byte_breaks_a_crc_and_the_label() { // Frame 4 of dnp3_read.pcap, TCP 51006 -> 20000: the 27-byte DNP3 // frame ends the Ethernet frame. let raw = hex::decode(DNP3_TCP_READ_REQUEST_20000_HEX).unwrap(); let start = raw.len() - 27; assert_eq!(raw[start..start + 2], [0x05, 0x64]); // One bit of the destination address: the header CRC no longer matches. let mut header = raw.clone(); header[start + 4] ^= 0x01; assert!(matches!( Dnp3Packet::try_from(&header[start..]), Err(Dnp3ParseError::HeaderCrcMismatch { actual: 0x0345, .. }) )); // One bit of an object header, in the first block of user data. let mut block = raw.clone(); block[start + 14] ^= 0x01; assert!(matches!( Dnp3Packet::try_from(&block[start..]), Err(Dnp3ParseError::BlockCrcMismatch { block: 0, actual: 0xac42, .. }) )); // On port 20000 itself, neither altered frame is DNP3 any more. for altered in [&header, &block] { let flow = parse(LinkType::ETHERNET, altered).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "Unknown"); assert!(flow.corrupted.is_none()); } } }
Oracle: 218 frames against tshark
The golden test tests/dnp3_golden.rs runs the sixteen captures of pcaps_exemple/protocols/dnp3/, taken from the test corpus of Zeek (BSD 3-clause, see the folder's SOURCE.md), and compares every segment and datagram that has a payload with tshark 4.6.6 without TCP reassembly, the view of a stateless parser (tools/dnp3_oracle.sh, frozen in tests/data/dnp3_tshark_oracle.tsv). Of 220 payloads, 218 are DNP3 frames, 179 on TCP and 39 on UDP, all labelled by the blind probe; the other two are the 05 05 segments of dnp3.pcap. On the 218 frames the link and transport headers match field by field: length, control, function, addresses, header CRC, FIR, FIN and sequence. 16 frames carry no user data; 159 application fragments fit in one frame, and their application header and 160 object headers, group, variation and the prefix and range codes of the qualifier, match too, except the objects of the four STOP_APPL of dnp3.pcap, which tshark does not dissect for that function; 7 first segments and 36 continuations belong to fragments spread over several frames.
A second test alters, one at a time, ten bytes of frame 4 of dnp3_read.pcap, from the second start byte to the block CRC: every altered frame is refused, by the decoder and by the probe, while the intact frame, moved to port 40000, stays DNP3. The fuzz target parse_dnp3 runs nightly on the same parser: the frames must tile the input, the user data have the length length announces, every object lies within the user data, and a single altered byte in any of four real frames must be refused. Since 11.7.0 it also mutates the user data alone, recomputing the CRCs, so that its mutations reach the transport, application and object headers; the frames of #180 and #182 are among its seeds, since its mutations do not forge the full range in practice.
| Capture | Frames | Content |
|---|---|---|
dnp3.pcap | 214 | nine TCP sessions between three pairs of hosts, eight in 2004 and one in 2007: class and object reads, writes, five selects of a CROB (g12v1) without an operate, restarts, stop application, enable and disable unsolicited, confirmations, solicited and unsolicited responses |
dnp3_read.pcap | 10 | read of classes 1, 2, 3 and 0, response with binary inputs, binary outputs and analog inputs |
dnp3_read_p20001.pcap | 10 | the same bytes, port rewritten to 20001 |
dnp3_write.pcap | 10 | write of the time and date (g50v1) |
dnp3_select_operate.pcap | 13 | select then operate of a binary command (g12v1, CROB) |
dnp3_en_spon.pcap | 10 | enable unsolicited (g60v2 to g60v4) |
dnp3_del_measure.pcap | 10 | delay measurement, response g52v2 |
dnp3_rec_time.pcap | 10 | record current time |
dnp3_file_read.pcap | 30 | open, read of its single block (g70v5, prefixed by its size), close |
dnp3_file_write.pcap | 22 | write of a file |
dnp3_file_del.pcap | 10 | deletion of a file |
dnp3_link_only.pcap | 35 | link status requests and replies, then a read whose response spans two application fragments over sixteen link frames |
dnp3_udp_read.pcap | 23 | a read over UDP 20000, whose response spans two application fragments over sixteen link frames |
dnp3_udp_write.pcap | 2 | write of g80v1 over UDP, clearing the restart indication |
dnp3_udp_select_operate.pcap | 10 | select then operate over UDP (g12v1), then a read whose response spans three link frames, and a link status request with its reply; no application confirmation |
dnp3_udp_en_spon.pcap | 4 | enable unsolicited over UDP (g60v2 to g60v4) |
One capture of the same Zeek folder is left out, dnp3-flowbuffer-overflow-assert.pcap: a scapy script generated it, and the corpus admits only real traffic.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- Object values are not decoded: no point value, flag, counter or time stamp, only where each object lies in
user_data. - No reassembly, at any level: neither the transport segments of a fragment, nor the fragments of a message, nor a link frame split over two TCP segments, which is labelled DNP3 in neither.
- Groups outside the table of annex A stop the object chain of a function that carries data; the header is kept, the rest is
undecoded. - Secure Authentication is named, not checked: functions 32, 33 and
0x83, and group 120, whose objects are sized by their prefix.
DNS
The Domain Name System (RFC 1035), with the two protocols that reuse its wire format on the local link: mDNS (RFC 6762) and LLMNR (RFC 4795). The module is packet_parser::parse::application::protocols::dns. DnsPacket has one constructor per form, and its errors are DnsPacketError, in packet_parser::errors::application::dns.
Detection: five rules, three labels
| Rule | Label | Transport | Port | Constructor |
|---|---|---|---|---|
| 11 | mDNS | UDP | 5353, terminal | DnsPacket::try_from_mdns |
| 12 | LLMNR | UDP | 5355, terminal | DnsPacket::try_from_llmnr |
| 22 | DNS | TCP | 53 | DnsPacket::try_from_tcp |
| 23 | DNS | UDP | 53 | DnsPacket::try_from |
| 53 | DNS | UDP | none | DnsPacket::is_blind_udp_match |
The three formats overlap on the wire. A unicast DNS query with RD set is a valid LLMNR header, since RD sits where LLMNR puts its T bit, and an mDNS query is a valid DNS query. Since 13.1.0 a recursive DNS response is a valid LLMNR header too: its RA bit falls in the Z bits, which an LLMNR receiver ignores. Only the port tells them apart, so each of the two link-local ports is terminal: when the probe of rule 14 or 15 refuses a datagram on its port, the dispatch stops and the flow has no application. A later rule would otherwise label a damaged mDNS message "DNS".
On port 53 the decoder alone decides. Off port 53, rule 59 asks for more, because a 12-byte header of plausible flags is weak evidence:
- the sections must end exactly where the datagram ends: a DNS message over UDP has no padding (RFC 1035 §4.2.1);
- the four counts must not all be zero.
Without them, the 37 datagrams of a radar feed in asterix/wireshark_8579_radardata.pcap, a header with four zero counts followed by 120 bytes, came out "DNS" (#118). There is no blind rule on TCP: off port 53, DNS over TCP needs a Decode As port. DecodeAsProtocol::Dns picks the datagram form on UDP and the length-prefixed form on TCP; Mdns and Llmnr exist too.
A query and its response, on port 53 and off it (tested):
#![allow(unused)] fn main() { #[test] fn a_response_repeats_the_question_and_points_back_to_its_name() { let raw = hex::decode(DNS_QUERY_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("DNS")); // 1060 -> 53 let query = DnsPacket::try_from(flow.transport.as_ref().unwrap().payload.unwrap()).unwrap(); assert_eq!(query.header.transaction_id, 0x180f); assert_eq!(query.header.flags, 0x0100); // a query, recursion desired assert_eq!(query.header.counts, [1, 0, 0, 0]); assert_eq!(query.queries.queries[0].name, "wireshark.org"); assert!(query.answers.is_none()); // an empty section is None let raw = hex::decode(DNS_RESPONSE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let response = DnsPacket::try_from(payload).unwrap(); assert_eq!(response.header.transaction_id, 0x180f); assert_eq!(response.header.counts, [1, 1, 0, 0]); // The answer's name is two bytes on the wire, c0 0c: a pointer to // offset 12, the name of the question. assert_eq!(payload[31..33], [0xc0, 0x0c]); let answer = &response.answers.as_ref().unwrap()[0]; assert_eq!(answer.name, "wireshark.org"); assert_eq!((answer.ttl, answer.data_length), (14400, 4)); assert_eq!(answer.address, [128, 121, 50, 122]); // the record data, raw // Off port 53 the blind rule still finds it: its sections end where // the datagram ends, and its counts are not all zero. let moved = with_ports(&raw, 40000, 40001); assert_eq!(label(&parse(LinkType::ETHERNET, &moved).unwrap()), Some("DNS")); } }
The message
#![allow(unused)] fn main() { #[non_exhaustive] pub struct DnsPacket<'a> { pub header: DnsHeader, // id, flags, four counts pub queries: DnsQueries, // the question section pub answers: Option<Vec<Answer<'a>>>, // None when the count is 0 pub authorities: Option<Vec<AuthoritativeNameServer<'a>>>, pub additionals: Option<Vec<AdditionalRecord<'a>>>, } }
DnsHeader keeps the transaction identifier, the flags as the raw u16 once they are checked, and counts, the four section counts in wire order. A question is a DnsQuery: name, qtype, qclass. A record of any of the three sections has the same fields: name, its type and class, ttl, data_length, and the record data as a borrowed slice, address in an Answer. DnsType and DnsClass are newtypes over u16 that display the IANA name when they know it.
The record data is not decoded. An A record's four bytes are ready to use; the target of a PTR or a CNAME is a name in wire form, compression pointers included, and stays that way.
Names and compression
A name is a sequence of labels, each a length byte and that many bytes, ended by a zero byte. A length byte whose two high bits are set is a pointer instead: with the next byte it gives an offset from the start of the message, where the name continues (RFC 1035 §4.1.4). In the diagram the answer's name is c0 0c, offset 12, the name of the question.
parse_dns_name rebuilds the name as a String, labels joined by dots, and bounds the work a hostile message can ask for:
| Rule | Refused as |
|---|---|
| A pointer must point strictly backwards | DnsQueryParseError::InvalidCompressionPointer |
| At most 8 pointers are followed for one name | InvalidCompressionPointer |
A length byte starting with 01 or 10 is reserved | ReservedLabelType |
| A name is at most 255 bytes on the wire, the labels reached through pointers included | OutOfBoundParse |
A label may hold any byte (RFC 2181 §11). Until 13.1.0 a single label outside UTF-8 made the whole message fail, and a query whose label carried ä in Latin-1 came out "Unknown" on UDP 53. Such a label now takes the presentation form of RFC 1035 §5.1: graphic ASCII as it is, . and \ escaped, any other byte as \DDD, so that the name reads j\228germeister #297. UTF-8 names do not change. The blind UDP probe still wants UTF-8 names: an escaped name is no proof there.
The 255-byte bound is the one of RFC 1035 §3.1, and tshark shows such a name as <Name too long>. It is also what bounds the cost of a message: before 11.7.0, records that all pointed to one very long question name had it read again each time, in time quadratic in the size of the message (#184). A name of exactly 255 bytes is accepted, one of 256 refused.
Since 11.7.0 the probes read the whole datagram and not its first 18 432 bytes (#185). A response larger than that is judged to its last byte, which is what the blind rule's "sections end where the datagram ends" needs.
Over TCP
Over TCP each message is preceded by its length on two bytes (RFC 1035 §4.2.2). try_from_tcp wants that length to cover at least a header and to fit in the segment, then decodes the first message. The length is also what tells DNS over TCP from an arbitrary payload on port 53 (tested):
#![allow(unused)] fn main() { #[test] fn dns_over_tcp_starts_with_a_length() { let raw = hex::decode(DNS_TCP_QUERY_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("DNS")); // 45818 -> 53 let payload = flow.transport.as_ref().unwrap().payload.unwrap(); assert_eq!(payload[..2], [0x00, 0x1a]); // 26: the message that follows assert_eq!(payload.len(), 2 + 26); let query = DnsPacket::try_from_tcp(payload).unwrap(); assert_eq!(query.queries.queries[0].name, "ripe.net"); // The datagram form takes the length for a transaction id, and // refuses the flags it reads two bytes too late. assert!(DnsPacket::try_from(payload).is_err()); // There is no blind rule on TCP: off port 53 the segment is unknown. let moved = with_ports(&raw, 40000, 40001); assert_eq!(label(&parse(LinkType::ETHERNET, &moved).unwrap()), Some("Unknown")); } }
mDNS and LLMNR
try_from_mdns relaxes two checks of unicast DNS. A responder announces its records without being asked, so a message may carry answers and no question; and RFC 6762 tells a receiver to ignore most header bits, so only a non-zero opcode or response code is refused.
try_from_llmnr applies the LLMNR header instead: opcode 0, a response code of at most 5 in a response, and the LLMNR counts, in a query no answer and no authority record. RFC 4795 §2.1.1 asks a receiver to ignore the four Z bits, and to take the response code of a query as zero. Until 13.1.0 the decoder refused both (InvalidZField, InvalidRCode), and such a query came out "Unknown" on UDP 5355; it now ignores them and keeps the flags as read #288.
An announcement that unicast DNS refuses, and a DNS response on the LLMNR port, a valid LLMNR header until its opcode changes (tested):
#![allow(unused)] fn main() { #[test] fn mdns_and_llmnr_ports_are_terminal() { let raw = hex::decode(MDNS_ANNOUNCEMENT_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("mDNS")); // 5353 -> 5353 // One answer and no question: unicast DNS refuses it, mDNS does not. let payload = flow.transport.as_ref().unwrap().payload.unwrap(); assert!(DnsPacket::try_from(payload).is_err()); let announcement = DnsPacket::try_from_mdns(payload).unwrap(); assert_eq!(announcement.header.counts, [0, 1, 0, 0]); let record = &announcement.answers.as_ref().unwrap()[0]; assert_eq!(record.name, "_dacp._tcp.local"); assert_eq!(record.ttl, 0); // a goodbye: the service is going away // Off port 5353 nothing labels it: the blind rule is the strict form. let moved = with_ports(&raw, 40000, 40001); assert_eq!(label(&parse(LinkType::ETHERNET, &moved).unwrap()), Some("Unknown")); // The wireshark.org response on the LLMNR port. Its RA bit falls in // the Z bits of LLMNR, which a receiver ignores (RFC 4795 §2.1.1): // since 13.1.0 the header is a valid LLMNR one. let raw = hex::decode(DNS_RESPONSE_HEX).unwrap(); let mut moved = with_ports(&raw, 5355, 1060); assert_eq!(label(&parse(LinkType::ETHERNET, &moved).unwrap()), Some("LLMNR")); // An opcode other than 0 is refused. The port is terminal: no later // rule is tried, and the flow has no application. moved[44] |= 0x10; // opcode 2, in the flags at byte 2 of the DNS header let flow = parse(LinkType::ETHERNET, &moved).unwrap(); assert!(flow.transport.is_some()); assert!(flow.application.is_none()); } }
Validations
The checks of DnsPacket::try_from, in order. Bytes count from the start of the message.
| Bytes | Field | Check | Error |
|---|---|---|---|
| 0–11 | Header | the message holds at least 12 bytes | DnsPacketError::InsufficientData |
| 2–3 | Flags, bit 6 | the one bit still reserved is zero; AD and CD are free | DnsFlagsError::InvalidZField |
| 2–3 | Flags, opcode | 0 to 5 | InvalidOpcode |
| 2–3 | Flags, RCODE | 0 to 5 | InvalidRCode |
| 2–3 | Flags, RA | zero in a query | RaInQuery |
| 2–3 | Flags, AA and TC | zero in the response to a STATUS request | AaTcInStatusResponse |
| 2–3 | Flags, AA | zero when the response code is 2 (server failure) or 5 (refused) | AaInServerFailure, AaInRefused |
| 4–11 | Counts | no record without a question | DnsHeaderError::InvalidCounts |
| 12– | Questions | each name follows the rules above, and four bytes of type and class follow it | DnsQueryParseError |
| after | Records | each name, then ten bytes of type, class, TTL and data length, then that many bytes of data | DnsQueryParseError |
Bytes after the last section are accepted on port 53. Only the blind rule refuses them.
Over TCP, try_from_tcp reads the two-byte length, then the first message of the segment. Since 13.1.0 a response may leave its question section empty, as the AXFR messages after the first do (RFC 5936 §2.2.1); a query still needs a question #297.
Oracle: counts and digests
DNS has no field-by-field oracle. tests/tshark_regression.rs compares, for the eleven captures of pcaps_exemple/protocols/dns/, the set of frames the crate labels "DNS" or "mDNS" with the frames of tshark -Y dns: 50 frames, a count and a digest of the frame numbers per capture. Two differences are named. In dns_axfr.pcapng and dns_tcp.pcapng, tshark also reports one message it reassembles from two segments; the crate labels the frames that hold a whole message.
tests/llmnr_golden.rs decodes real LLMNR queries of The-Ultimate-PCAP.pcapng, and checks that a DNS query of the same capture is a valid LLMNR header too. The golden histogram counts 104 DNS, 136 LLMNR and 12 mDNS labels.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- The record data. No record type is decoded: an address, a name, an SOA or an OPT pseudo-record all come out as bytes.
- Response codes above 5 and opcodes above 5. They are refused, so a dynamic update that answers
NOTAUTHis not"DNS". - A message over several TCP segments. A zone transfer larger than a segment is recognized in the segments that start with a whole message;
try_from_tcpreads the first message of a segment and stops. - Pairing. Nothing matches a response to its query by transaction identifier.
- DNS over TLS, HTTPS or QUIC. They are labelled by their envelope.
GIOP
GIOP (General Inter-ORB Protocol) is the wire protocol of CORBA. It is the most complete application decoder of the crate, and the one whose development taught the most about parsing real traffic: two bugs were only found when the parser met genuine captures, and the final shape of the decoder — accept truncated messages, walk consecutive messages in a segment, resynchronize in the middle of a stream — comes straight from what an ORB actually puts on the wire. This chapter walks through it as a worked example of the method described in the previous chapters.
Module: packet_parser::parse::application::protocols::giop. Specification: CORBA formal/04-03-12, chapter 15. Supported: GIOP 1.0, 1.1 and 1.2, the eight message types, both endiannesses.
The message
The header is 12 bytes: the GIOP magic, the version, a flags byte, the message type, and the size of the body. That size is not in a fixed byte order: bit 0 of the flags says which. Frame 19 of corba.pcap, drawn here, is the message that taught the parser this lesson (below).
#![allow(unused)] fn main() { pub struct GiopPacket<'a> { pub header: GiopHeader, pub payload: GiopMessage<'a>, /// The buffer does not hold the whole body announced by `message_length`. pub truncated: bool, // bytes of the buffer covered by this message, header included } pub enum GiopMessage<'a> { Request(GiopRequest<'a>), Reply(GiopReply<'a>), CancelRequest(GiopCancelRequest), LocateRequest(GiopLocateRequest<'a>), LocateReply(GiopLocateReply<'a>), CloseConnection, // header only MessageError, // header only Fragment(GiopFragment<'a>), /// Valid type, unreadable body: the header stays reliable. Other, } }
Reading it
#![allow(unused)] fn main() { use packet_parser::parse::application::protocols::giop::{GiopMessage, GiopPacket, TargetAddress}; let packet = GiopPacket::try_from(tcp_payload)?; let h = &packet.header; println!("GIOP 1.{} {:?} little_endian={} size={} truncated={}", h.minor_version, h.message_type, h.is_little_endian(), h.message_length, packet.truncated); if let GiopMessage::Request(request) = &packet.payload { println!("Request id={} op={} contexts={} stub={} bytes", request.request_id, request.operation, request.service_contexts.len(), request.stub_data.len()); if let TargetAddress::KeyAddr(key) = &request.target { println!("target object key: {} bytes", key.len()); } } }
On frame 4 of pcaps_exemple/protocols/giop/corba.pcap (the nDPI test corpus), this prints:
GIOP 1.2 Request little_endian=false size=216 truncated=false
Request id=0 op=echo contexts=1 stub=76 bytes
target object key: 60 bytes
and flow.application is labelled "GIOP" by the pipeline, through a blind TCP probe: the literal magic, a version in 1.0..1.2 and a known message type make a strong enough signature.
The book's example crate checks every one of these values on that frame — this is the test that pins down the difference between the pipeline's classification and the protocol parser's decode (tested):
#![allow(unused)] fn main() { #[test] fn classification_is_a_label_the_protocol_parser_is_the_decode() { let raw = hex::decode(ETHERNET_IPV4_TCP_GIOP_REQUEST_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); // The pipeline classifies the transport payload: a label, no decode. assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "GIOP"); // The detailed parser decodes the same bytes. let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = GiopPacket::try_from(payload).unwrap(); assert_eq!(packet.header.minor_version, 2); assert_eq!(packet.header.message_type, GiopMessageType::Request); assert!(!packet.header.is_little_endian()); assert_eq!(packet.header.message_length, 216); assert!(!packet.truncated); let GiopMessage::Request(request) = &packet.payload else { panic!("expected a Request, got {:?}", packet.payload); }; assert_eq!(request.request_id, 0); assert_eq!(request.operation, "echo"); assert_eq!(request.service_contexts.len(), 1); assert_eq!(request.stub_data.len(), 76); let TargetAddress::KeyAddr(key) = &request.target else { panic!("expected a KeyAddr target"); }; assert_eq!(key.len(), 60); } }
The header: a TryFrom like the others
#![allow(unused)] fn main() { impl TryFrom<&[u8]> for GiopHeader { type Error = GiopParseError; fn try_from(payload: &[u8]) -> Result<Self, Self::Error> { ensure_min_len(payload)?; // 12 bytes let magic = parse_magic(payload)?; // "GIOP" let (major_version, minor_version) = extract_version(&payload[4..6])?; // 1.0..1.2 let flags = extract_flags(&payload[6])?; let message_type = GiopMessageType::try_from(payload[7])?; // 0..7 validate_message_type_in_version(payload[7], minor_version)?; // Fragment needs 1.1+ let message_length = extract_message_size(&payload[8..12], flags & 0x01 != 0)?; Ok(GiopHeader { magic, major_version, minor_version, flags, message_type, message_length }) } } }
Two details in this sequence are lessons from real frames:
message_sizefollows the endianness announced by the flags. The first version of the parser read it big-endian unconditionally. Frame 19 ofcorba.pcap, a little-endian Request carried inside a MIOP datagram, announced a size of0xD8000000and was rejected. GIOP 1.0 calls that bytebyte_order, a boolean; GIOP 1.1+ calls itflagswith the same bit at the same place.- The domain of a field depends on the version. Message type 7 (Fragment) does not exist in GIOP 1.0; reply status 4 and 5 (
LOCATION_FORWARD_PERM,NEEDS_ADDRESSING_MODE) and locate status 3..5 only exist in 1.2. Accepting them on an older header would produce a "valid" struct that contradicts itself, sovalidate_reply_status(value, minor_version)and friends take the version.
The body is CDR: a cursor, not indexes
The header is fixed; the body is CDR (Common Data Representation), CORBA's serialization. Its rule: every primitive is aligned on its natural size, counted from the start of the CDR stream. A ulong after a 2-byte short is preceded by 2 bytes of padding. Strings and sequence<octet> are length-prefixed. The layout of a Request also changed between GIOP 1.1 and 1.2 (service contexts moved from the front to after the operation name, object_key became a TargetAddress union, requesting_principal was removed, and the stub data became aligned on 8).
Indexing into the body with fixed offsets is therefore impossible. The module uses a small crate-internal cursor:
#![allow(unused)] fn main() { pub(super) struct Cursor<'a> { buf: &'a [u8], pos: usize, base: usize, // 12 for a message body: alignment counts from the header little_endian: bool, } impl<'a> Cursor<'a> { fn align(&mut self, boundary: usize); // CDR padding, bounded by the buffer fn align_body_1_2(&mut self); // Request/Reply 1.2 body aligned on 8 fn read_u8(&mut self) -> Result<u8, GiopParseError>; fn read_u16(&mut self) -> Result<u16, GiopParseError>; // align(2) first fn read_u32(&mut self) -> Result<u32, GiopParseError>; // align(4) first fn read_bytes(&mut self, len: usize) -> Result<&'a [u8], GiopParseError>; fn read_octet_sequence(&mut self) -> Result<&'a [u8], GiopParseError>; // ulong len + bytes fn read_str(&mut self) -> Result<&'a str, GiopParseError>; // + UTF-8, trailing NUL dropped fn rest(&self) -> &'a [u8]; } }
Every read checks ensure_available first and returns UnexpectedEof otherwise: the cursor is the one place where bounds are enforced, and the parsers above it never index the buffer. It stays zero-copy: read_bytes, read_octet_sequence and read_str return slices of the original buffer, and rest() is how stub_data and body are obtained.
The second bug found on real frames lives here. The TargetAddress discriminant is a CDR short (2 bytes, followed by 2 bytes of padding before the next ulong), not an octet. Read as one byte, no real GIOP 1.2 Request decoded. The golden tests on corba.pcap lock these paddings in: without them, the operation name and service contexts of every real Request come out shifted.
The body of frame 4, the Request of the example above. The message starts 12 bytes earlier, and 12 is a multiple of 4, so each 4-byte alignment falls at the start of a row here. The hatched bytes are the padding: the 2 after the short discriminant are the ones the first version did not skip.
The base field handles a subtlety: the alignment of a message body counts from the start of the message, header included (offset 0 is the magic), while an encapsulation — the opaque profile_data of an IOR profile — is its own CDR stream, starting at its own endianness byte. Cursor::encapsulation() restarts at base 0 and reads that byte.
A Request in GIOP 1.2 then reads as:
#![allow(unused)] fn main() { pub fn parse(body: &'a [u8], little_endian: bool) -> Result<Self, GiopParseError> { let mut cur = Cursor::new(body, little_endian); let request_id = cur.read_u32()?; let response_flags = cur.read_u8()?; let _reserved = cur.read_bytes(3)?; let target = parse_target_address(&mut cur)?; // short discriminant + KeyAddr / ProfileAddr / ReferenceAddr let operation = cur.read_str()?; let service_contexts = parse_service_context_list(&mut cur)?; cur.align_body_1_2(); // padding to 8, only if a body follows Ok(GiopRequest { request_id, response_flags, target, operation, service_contexts, requesting_principal: None, stub_data: cur.rest() }) } }
and the 1.0/1.1 layout is a separate function with the historical order, mapped onto the same struct (response_expected lands in response_flags, object_key becomes TargetAddress::KeyAddr).
Sender-controlled counters are bounded before allocation
A service context list and an IOR profile list are ulong count followed by count entries, and each entry is at least 8 bytes. A hostile count of 0xFFFFFFFF must not drive a Vec::with_capacity. The checks module bounds every counter against the bytes remaining before the loop:
#![allow(unused)] fn main() { pub fn validate_service_context_count(count: usize, remaining: usize) -> Result<(), GiopParseError> { if count > remaining / SERVICE_CONTEXT_MIN_LEN { return Err(GiopParseError::InvalidServiceContextCount { count, available: remaining }); } Ok(()) } }
Typed replies, degraded gracefully
A Reply carries a reply_status, and the meaning of its body depends on it. The decoder types that:
#![allow(unused)] fn main() { pub enum GiopReplyDetail<'a> { Results, // NO_EXCEPTION: IDL-typed, opaque UserException { exception_id: &'a str, members: &'a [u8] }, SystemException(GiopSystemException<'a>), // repository id, minor code, completion status LocationForward(Ior<'a>), // the reference to retry against NeedsAddressingMode(u16), Undecoded, // body unreadable, raw bytes kept in `body` } }
LocationForward is the interesting one for an analyst: the IOR says which host and port the client is being redirected to. Ior::iiop() returns the first readable IIOP profile — host, port, object key — decoded from its encapsulation:
#![allow(unused)] fn main() { if let GiopMessage::Reply(reply) = &packet.payload && let GiopReplyDetail::LocationForward(ior) = &reply.detail && let Some(iiop) = ior.iiop() { println!("redirected to {}:{} ({})", iiop.host, iiop.port, ior.type_id); } }
Every level degrades on its own. An unreadable IIOP profile does not fail the IOR (iiop() returns None); an unreadable body does not fail the Reply (detail becomes Undecoded, the header and status are already reliable); an unreadable Request body does not fail the packet (payload becomes GiopMessage::Other). The reason is the pipeline: the blind probe calls GiopPacket::try_from on arbitrary TCP traffic, and the decode depth of the body must not change the classification, which only the header earns.
Stateless, on a protocol that ignores segment boundaries
GIOP messages routinely exceed the TCP MSS: an 8 KiB push Request on a 1460-byte segment is four segments. The parser is stateless — no TCP reassembly, no Fragment reassembly — so three behaviours were chosen deliberately:
- A message that overflows its segment is accepted and flagged, not rejected. The first segment carries the complete header and usually the complete Request header (request id, operation, object key), which is exactly what an analyst wants.
truncatedis set,wire_len()is bounded by the buffer, and the body is decoded on the bytes present. Before this choice, the first segment of every large message came outUnknownfrom the pipeline. - A segment may hold several messages. An ORB happily chains short messages (a LocateRequest and a Request) in one segment.
giop_messages(payload)iterates over them, stopping at the first byte that does not open a valid message or after a truncated one. - A message may start in the middle of a continuation segment. After a large message, the next one begins at offset 952 of a segment that does not start with the magic, and the stateless pipeline cannot label that segment. A caller that tracks flows and already knows the stream is GIOP can resynchronize with
find_giop_message(payload), which returns the offset of the first valid header (magic, version, type, reserved flag bits at zero), then read withgiop_messages. It is also how the GIOP message inside a MIOP multicast datagram is reached. It is not for classifying unknown traffic: four magic bytes in the middle of application data prove nothing.
Verified against tshark, message by message
The unit tests build synthetic bodies for the cases no ORB at hand emits (CancelRequest, OBJECT_FORWARD_PERM, ReferenceAddr...). Everything else is verified on real captures under pcaps_exemple/protocols/giop/, each with its provenance in SOURCE.md:
corba.pcapfrom the nDPI test corpus: GIOP 1.2 over TCP and over MIOP, both endiannesses, plus a ZIOP (compressed) message;- three captures attached to public Wireshark bug reports: LocateRequest/LocateReply, a fragmented 8 KiB Request whose Fragments start mid-segment, a GIOP 1.0
LOCATION_FORWARDwith an IIOP profile, aUSER_EXCEPTIONfrom CosNaming; - seven
lab_*.pcapproduced bytools/capture_giop.sh: a real omniORB 4.3.3 server and clients in a throwaway container, scripted to emit the same scenario in GIOP 1.0, 1.1 and 1.2, plus system exceptions, CloseConnection, MessageError and a client timeout. The recipe is replayable.
tests/giop_tshark_regression.rs replays every capture and compares each message, column by column, with an oracle produced by tools/giop_oracle.sh — tshark 4.6.6 with TCP reassembly disabled, i.e. the view of a stateless parser: type, version, flags, size, request id, reply and locate status, operation, exception id, IIOP host and port, object key and stub data lengths. The known divergences (tshark reports no request id on a 1.1 Fragment, and no operation on any Fragment) are named in tshark_only_columns, not hidden. A larger corpus (1 641 messages from other Wireshark issues), too big to redistribute, is replayed by an #[ignore] test.
The fuzz target parse_giop runs find_giop_message, then giop_messages, then dereferences every IOR it finds, asserting that no message ever covers more bytes than the buffer holds and that the iteration always progresses.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- Stub data and user-exception members are IDL-typed: without the IDL they are opaque, and kept as raw slices.
- IIOP 1.1+ tagged components in a profile are not decoded.
- ZIOP (compressed GIOP) and MIOP framing are recognized as such but not decoded: the ZIOP body needs decompression, and MIOP is reached through
find_giop_message. - No reassembly, by design. Fragments are decoded individually (
GiopFragmentcarries the request id from 1.2 on); reassembling them belongs to a stateful layer above the parser.
HTTP
HTTP/1.x (RFC 9112), as it fits in one TCP segment: the crate reassembles nothing. The module is packet_parser::parse::application::protocols::http, and its errors are HttpParseError, in packet_parser::errors::application::http. Since 11.7.0 it has two decoders, HttpRequest and HttpResponse (#176), and both borrow everything from the payload:
#![allow(unused)] fn main() { pub struct HttpRequest<'a> { pub method: &'a str, pub uri: &'a str, pub version: &'a str, // "HTTP/1.1", "HTTP/1.0"... pub headers: HttpHeaders<'a>, pub body: &'a str, // the body as text, empty when it is not UTF-8 pub body_bytes: &'a [u8], // the body as carried, since 11.7.0 } pub struct HttpResponse<'a> { pub version: &'a str, pub status_code: u16, // three digits pub reason: &'a str, // possibly empty pub headers: HttpHeaders<'a>, pub body: &'a [u8], } }
Both are #[non_exhaustive]. HttpHeaders is the view over the header block that both share, validated once while parsing: iter() gives the (name, value) pairs in wire order, get(name) the first value of a name compared case-insensitively, and neither allocates.
Detection: requests and responses
The rule is a blind probe on TCP, rule(ApplicationProtocol::Http, Guard::Tcp, ProbeId::Http), rule 64 of the table, after the first SSH rule and the SIP rule, before the second SSH rule and GIOP; no port is involved. The SSH rule after it, added in 13.1.0, reads a banner behind other lines, so that an HTTP response whose body quotes a banner stays HTTP. Before 11.7.0 the probe was HttpRequest::try_from alone: a response came out "Unknown" while the request that caused it came out "HTTP", and since the whole payload had to be valid UTF-8, so did a request whose binary body fitted in the same segment. The probe now accepts either of two start lines:
- a request line: a method among GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE and PATCH, a URI, and a version,
HTTP/then one digit, or two separated by a dot; - a status line (RFC 9112 §4): the same version, a code of exactly three digits, and a reason phrase, possibly empty.
Header lines follow, each with a colon, up to the first CRLF CRLF. Only this head must be valid UTF-8, for requests as for responses; the body is taken as it is, an image, gzip or a piece of a chunked transfer. The probe reads the first PROBE_CAP bytes of the payload (invariant 3), and without a CRLF CRLF in them, all of them are the head.
The body is not decoded: no chunk is reassembled, nothing is decompressed, and nothing checks it against Content-Length, so a body cut by the segment is what follows the head in this one. HTTP/2 and HTTP/3 have no decoder, and HTTP inside TLS is labelled TLS: the crate does not decrypt.
Frame 30 of pcaps_exemple/protocols/arp/arppoison.pcapng, a server's 204 No Content, came out "Unknown" in 11.6.0 (tested):
#![allow(unused)] fn main() { #[test] fn an_http_response_is_labelled_http() { let raw = hex::decode(HTTP_NO_CONTENT_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("HTTP")); // 80 -> 45691: the blind rule, no port let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let response = HttpResponse::try_from(payload).unwrap(); assert_eq!(response.version, "HTTP/1.1"); assert_eq!((response.status_code, response.reason), (204, "No Content")); assert_eq!(response.headers.len(), 7); assert_eq!(response.headers.get("content-length"), Some("0")); // any case assert_eq!(response.headers.get("Server"), Some("Golfe")); assert!(response.body.is_empty()); // A status line is not a request line: the probe tries both decoders. assert!(HttpRequest::try_from(payload).is_err()); } }
Frame 21178 of pcaps_exemple/The-Ultimate-PCAP.pcapng is an OCSP request to Let's Encrypt over IPv6, whose 85-byte DER body is in the same segment; because of that body, it came out "Unknown" in 11.6.0 (tested):
#![allow(unused)] fn main() { #[test] fn a_request_with_a_binary_body_is_http() { let raw = hex::decode(HTTP_OCSP_REQUEST_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("HTTP")); // 55996 -> 80 let payload = flow.transport.as_ref().unwrap().payload.unwrap(); assert!(std::str::from_utf8(payload).is_err()); // the segment is not all text let request = HttpRequest::try_from(payload).unwrap(); assert_eq!((request.method, request.uri, request.version), ("POST", "/", "HTTP/1.0")); assert_eq!(request.headers.get("host"), Some("ocsp.int-x3.letsencrypt.org:80")); assert_eq!(request.headers.get("Content-Type"), Some("application/ocsp-request")); assert_eq!(request.headers.get("Content-Length"), Some("85")); // The body is a DER OCSPRequest, a SEQUENCE of 0x53 bytes. It is not // UTF-8: `body` is empty, and `body_bytes` carries the 85 bytes. assert_eq!(request.body, ""); assert_eq!(request.body_bytes.len(), 85); assert_eq!(request.body_bytes[..2], [0x30, 0x53]); } }
What is not HTTP
The rule has no port, so its start line is all that keeps other text protocols out. Each row was checked against the crate, on TCP:
| Payload starts with | Label | Why |
|---|---|---|
get / HTTP/1.1 | "Unknown" | methods are upper case |
PROPFIND / HTTP/1.1, NOTIFY * HTTP/1.1 | "Unknown" | the method is not one of the nine |
PRI * HTTP/2.0, the HTTP/2 preface | "Unknown" | PRI is not one of the nine |
OPTIONS rtsp://… RTSP/1.0 | "Unknown" | the version does not start with HTTP/ |
INVITE sip:… SIP/2.0 | "SIP" | neither the method nor the version is HTTP's; since 13.2.0 the SIP rule, just before, labels a complete message |
ICY 200 OK | "Unknown" | a status line starts with HTTP/ |
HTTP/1.1 20 OK | "Unknown" | the code is not three digits |
| a header line without a colon | "Unknown" | HttpParseError::InvalidHeader |
| a head that is not UTF-8 | "Unknown" | HttpParseError::InvalidUtf8 |
On UDP nothing is HTTP: the rule has a TCP guard. NOTIFY and M-SEARCH on UDP 1900 are SSDP, rule 16.
Three shapes are accepted that a strict reader would refuse: a start line with no header after it, line ends that are LF alone, and a status line with no reason phrase. HTTP/2 200 is accepted too, since the version is one digit or two; it is a line no HTTP/2 connection carries in clear.
Validations
The head is text, so the table counts lines, not bytes.
| Part | Check | Error |
|---|---|---|
| Head | valid UTF-8, up to the first empty line or the end of what the probe reads | HttpParseError::InvalidUtf8 |
| Request line | three parts: method, URI, version | MissingMethod, MissingUri, MissingVersion |
| Method | GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE or PATCH | InvalidMethod, with the text |
| Version | HTTP/, then one digit, or two separated by a dot | InvalidVersion, with the text |
| Status line | a version, then a code | MissingVersion, MissingStatusCode |
| Status code | exactly three digits | InvalidStatusCode, with the text |
| Header line | a colon | InvalidHeader |
Oracle: 298 frames
tests/http_golden.rs compares the crate with tshark 4.6.9 without TCP reassembly, the view of a stateless parser (tools/http_oracle.sh, frozen in tests/data/http_tshark_oracle.tsv). For each frame it checks the kind, the version, and the method and URI or the code and phrase. It runs on every capture of pcaps_exemple/protocols/ and on The-Ultimate-PCAP.pcapng: 145 requests and 153 responses match. The last two came with 13.2.0: protocols/sip/ndpi_http_on_sip_port.pcap, from the nDPI test corpus, is a GET and its 403 on TCP 5060, the port of SIP. tshark dissects that port as SIP, so tools/http_oracle.sh declares it HTTP with -d tcp.port==5060,http, and the crate labels both frames "HTTP".
The crate labels no other frame of these captures "HTTP", retransmissions apart. tshark does not dissect a retransmission; the crate labels six of them like the segments they repeat, and they are left out of the comparison. The two responses that tshark decrypts in tls12-dsb.pcapng, with the key the capture carries, stay TLS.
With 11.7.0 the golden histogram went from 72 to 146 HTTP labels: 72 responses more, and 2 retransmissions of responses. "Unknown" went from 9 579 to 9 505. With 13.2.0 the two frames of the SIP negative bring it to 148.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- The body. No chunk is reassembled, nothing is decompressed, and nothing checks the body against
Content-Length: a body cut by the segment is what follows the head in this one. - A message over several segments. The crate reassembles nothing. A head cut between two header lines, or after the colon of one, is read as far as it goes; cut before the colon of a header line, the segment is
"Unknown". So are the segments that carry the rest of the message, which start with no request or status line. - Other methods. A WebDAV
PROPFINDor any extension method is not recognized. The response to it still is: a response is recognized on its own status line. - HTTP/2 and HTTP/3. They have no decoder.
- HTTP inside TLS. It is labelled TLS: the crate does not decrypt.
- Retransmissions. A retransmitted segment is labelled like the one it repeats, and counted again.
IEC 60870-5-104
IEC 60870-5-104 is the telecontrol protocol of the European electric sector, the counterpart of DNP3: the messages of IEC 60870-5-101 over TCP 2404, the IANA port iec-104. It was added in 11.6.0 (#158), in the epic #102 with BACnet/IP and GOOSE. The module is packet_parser::parse::application::protocols::iec104, the errors are in packet_parser::errors::application::iec104, and the label is "IEC 104".
A TCP segment carries one or more APDUs. Each one starts with its APCI, 0x68, a length and a four-byte control field whose format is I, S or U; an I-format APDU then carries an ASDU: a type, a cause of transmission, a common address and its information objects. The crate reads them without state, and an APDU that the segment cuts short is decoded on what is left of it.
Detection: port 2404, or Decode As
Unlike DNP3, IEC 104 is not probed blind. The APCI has no CRC, and what is fixed in it, 0x68 and a length, is two bytes: too little to probe every TCP segment with. The rule is port-guarded, port_rule(ApplicationProtocol::Iec104, Guard::Tcp, is_iec104_tcp_port, ProbeId::Iec104), 2404 on either side, rule 34 of the table, among the port rules after RDP and before Java RMI. As for every port rule, the port is not enough: Iec104Packet::try_from must accept the payload, read whole rather than cut at PROBE_CAP. A station on another port is declared with ParseConfig::decode_as(port, DecodeAsProtocol::Iec104), the variant added in 11.6.0, which is tried before the table with the same probe and the same TCP guard. Off those ports nothing recognizes IEC 104: classify_payload called with no port (None, None) skips every port rule, this one included.
The same interrogation on 2404, on 2405, then on 2405 declared (tested):
#![allow(unused)] fn main() { #[test] fn iec104_needs_port_2404_or_a_decode_as() { // Frame 9 of wireshark_iec104.pcap: TCP 46413 -> 2404. let raw = hex::decode(IEC104_INTERROGATION_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "IEC 104"); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = Iec104Packet::try_from(payload).unwrap(); let [apdu] = &packet.apdus[..] else { panic!("expected one APDU"); }; assert_eq!(apdu.length, 14); assert_eq!( apdu.format, ApciFormat::Information { send_sequence: 0, receive_sequence: 0 } ); // A general interrogation (C_IC_NA_1), cause 6 (activation), station 10. let asdu = apdu.asdu.as_ref().unwrap(); assert_eq!((asdu.type_id, asdu.kind), (100, Some(AsduType::CIcNa1))); assert_eq!((asdu.sequence, asdu.count), (false, 1)); assert_eq!((asdu.cause, asdu.negative, asdu.test), (6, false, false)); assert_eq!((asdu.originator, asdu.common_address), (0, 10)); let [object] = &asdu.objects[..] else { panic!("expected one information object"); }; assert_eq!(object.address, 0); assert_eq!(object.element, [20]); // QOI 20: station interrogation assert!(asdu.undecoded.is_empty()); // The same segment, destination port rewritten to 2405: the bytes of // the APDU have not changed, but no rule guards that port. let mut moved = raw.clone(); moved[36..38].copy_from_slice(&2405u16.to_be_bytes()); let flow = parse(LinkType::ETHERNET, &moved).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "Unknown"); // Declared by the caller, the port is tried first, content included. let config = ParseConfig::new().decode_as(2405, DecodeAsProtocol::Iec104); let flow = parse_with(LinkType::ETHERNET, &moved, &config).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "IEC 104"); } }
The APCI
#![allow(unused)] fn main() { pub struct Iec104Packet<'a> { pub apdus: Vec<Apdu<'a>>, pub truncated: bool, // the last APDU announces more than the segment holds } pub struct Apdu<'a> { pub length: u8, // control field and ASDU, not the first two bytes pub control: [u8; 4], pub format: ApciFormat, pub asdu: Option<Asdu<'a>>, // None for S and U, and for an I APDU cut // before the end of its ASDU header } pub enum ApciFormat { Information { send_sequence: u16, receive_sequence: u16 }, // numbered, carries an ASDU Supervisory { receive_sequence: u16 }, // acknowledgement only Unnumbered(UnnumberedFunction), // link control } }
Like every public type of the module, they are #[non_exhaustive].
| Bytes | Field | Note |
|---|---|---|
| 0 | start | 0x68, otherwise InvalidStartByte |
| 1 | length | the control field and the ASDU: 4 to 253, otherwise InvalidLength |
| 2–5 | control | read according to the format, which the two low bits of byte 2 give |
| Format | Byte 2, low bits | What the crate reads | ApciFormat |
|---|---|---|---|
| I | x0 | N(S) in bytes 2–3 and N(R) in bytes 4–5, each shifted left by one bit | Information { send_sequence, receive_sequence } |
| S | 01 | N(R) in bytes 4–5 | Supervisory { receive_sequence } |
| U | 11 | the function bits of byte 2 | Unnumbered(function) |
The sequence numbers are read little-endian and shifted back, 15 bits each. The first control byte of a U-format APDU must carry exactly one of the six functions, otherwise it is InvalidUnnumberedFunction: STARTDT act 0x04 and con 0x08, STOPDT act 0x10 and con 0x20, TESTFR act 0x40 and con 0x80, the variants StartDtAct to TestFrCon of UnnumberedFunction, whose bits() gives the value back. An S or U APDU is its control field alone: a length other than 4 is ControlOnlyFormat { format, length }, with format "S" or "U".
Iec104Packet::try_from reads the APDUs back to back until the segment is consumed: in the corpus, 448 APDUs in 373 segments, 40 of which carry more than one, up to twelve in frame 16 of wireshark_iec104.pcap. Each needs its six bytes of APCI, or the decode fails with Truncated { expected: 6, actual }, an empty payload included.
The three formats, and a segment of three APDUs (tested):
#![allow(unused)] fn main() { #[test] fn iec104_the_control_field_gives_the_format() { // Frame 7 of wireshark_iec104.pcap: U format, STARTDT act. let raw = hex::decode(IEC104_STARTDT_ACT_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = Iec104Packet::try_from(payload).unwrap(); let startdt = &packet.apdus[0]; assert_eq!((startdt.length, startdt.control), (4, [0x07, 0x00, 0x00, 0x00])); assert_eq!( startdt.format, ApciFormat::Unnumbered(UnnumberedFunction::StartDtAct) ); assert!(startdt.asdu.is_none()); // Frame 15: S format, an acknowledgement with N(R) 13. let raw = hex::decode(IEC104_S_FORMAT_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = Iec104Packet::try_from(payload).unwrap(); assert_eq!(packet.apdus[0].format, ApciFormat::Supervisory { receive_sequence: 13 }); assert!(packet.apdus[0].asdu.is_none()); // Frame 12: three I-format APDUs in one 72-byte segment. let raw = hex::decode(IEC104_THREE_APDUS_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = Iec104Packet::try_from(payload).unwrap(); assert_eq!(packet.apdus.len(), 3); assert!(!packet.truncated); let numbers: Vec<(u16, u16)> = packet .apdus .iter() .map(|apdu| match apdu.format { ApciFormat::Information { send_sequence, receive_sequence } => { (send_sequence, receive_sequence) } other => panic!("expected the I format, got {other:?}"), }) .collect(); assert_eq!(numbers, [(1, 1), (2, 1), (3, 1)]); let asdus: Vec<_> = packet.apdus.iter().map(|apdu| apdu.asdu.as_ref().unwrap()).collect(); let kinds: Vec<_> = asdus.iter().map(|asdu| (asdu.kind, asdu.cause)).collect(); assert_eq!( kinds, [ (Some(AsduType::CIcNa1), 7), // the interrogation is confirmed (Some(AsduType::MSpNa1), 20), // single points, interrogated (Some(AsduType::MDpNa1), 20), // double points, interrogated ] ); // Not in sequence: every object carries its own address, then its // one-byte element (the quality descriptor and the value). let single = asdus[1]; assert!(!single.sequence); let addresses: Vec<u32> = single.objects.iter().map(|object| object.address).collect(); assert_eq!(addresses, [1, 2, 3, 4]); assert!(single.objects.iter().all(|object| object.element.len() == 1)); } }
The ASDU
#![allow(unused)] fn main() { pub struct Asdu<'a> { pub type_id: u8, pub kind: Option<AsduType>, // the type, named by its IEC 60870-5-101 mnemonic pub sequence: bool, // SQ: one address, then contiguous elements pub count: u8, // objects or elements announced pub cause: u8, // cause of transmission, six bits pub negative: bool, // P/N pub test: bool, // T pub originator: u8, pub common_address: u16, pub objects: Vec<InformationObject<'a>>, pub undecoded: &'a [u8], // what follows the objects read } pub struct InformationObject<'a> { pub address: u32, // three bytes; in sequence, the first plus the rank pub element: &'a [u8], } }
The header is the one of IEC 60870-5-101 with the parameters of -104: a cause of transmission on two bytes, a common address on two, an information object address on three.
| Bytes of the ASDU | Field | Note |
|---|---|---|
| 0 | type_id | named by kind |
| 1 | sequence (bit 7), count (bits 0–6) | a count of zero is EmptyAsdu(type_id) |
| 2 | cause (bits 0–5), negative (bit 6), test (bit 7) | for instance 6 an activation, 7 its confirmation, 20 an answer to the interrogation, which tshark names Act, ActCon and Inrogen |
| 3 | originator | originator address |
| 4–5 | common_address | little-endian |
| 6… | information objects |
A complete I-format APDU whose ASDU is shorter than these six bytes is AsduTooShort. AsduType names 67 type identifications, codes 1 to 21, 30 to 40, 45 to 51, 58 to 64, 70, 100 to 107, 110 to 113 and 120 to 127, after their mnemonic: MSpNa1 for M_SP_NA_1, CIcNa1 for C_IC_NA_1, the first letter M for information in monitoring direction, C for a command, P for a parameter, F for file transfer. AsduType::from_code maps a code to its variant, and an unknown code leaves kind at None.
Each object is an address on three bytes, little-endian, and an element whose size the type fixes, from a table of IEC 60870-5-101 §7.3 internal to the crate: one byte for a single or double point, five for a short floating-point measurement, and the time tag counts, 3 bytes for a CP24Time2a and 7 for a CP56Time2a: M_SP_TB_1 is 8 bytes. With SQ = 0 every object carries its address; with SQ = 1 only the first address is on the wire, followed by count elements, and the crate numbers the objects address + rank. element borrows the segment, raw: quality descriptor, value and time tag together.
The objects are read while they fit, and the rest of the ASDU is undecoded: nothing when everything was read, all of it when the crate has no element size for the type: an unknown type and, among the named ones, type 125, the file segment, and type 127. The decoder does not require the objects to fill the APDU exactly; in the corpus, every one of the 301 ASDUs has exactly count objects and nothing undecoded.
An ASDU in sequence (tested):
#![allow(unused)] fn main() { #[test] fn iec104_an_asdu_in_sequence_carries_one_address() { // Frame 1 of wireshark_IEC104_SQ.pcapng: TCP 2404 -> 4446. let raw = hex::decode(IEC104_SEQUENCE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "IEC 104"); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); assert_eq!(payload.len(), 124); let packet = Iec104Packet::try_from(payload).unwrap(); assert_eq!(packet.apdus.len(), 4); for (index, apdu) in packet.apdus.iter().enumerate() { // Control field, ASDU header, one address, sixteen elements. assert_eq!(apdu.length, 4 + 6 + 3 + 16); let asdu = apdu.asdu.as_ref().unwrap(); assert_eq!(asdu.kind, Some(AsduType::MSpNa1)); assert!(asdu.sequence); assert_eq!((asdu.count, asdu.cause, asdu.common_address), (16, 20, 1054)); // Only the first address is on the wire; the others are counted. let first = 16 * index as u32; let addresses: Vec<u32> = asdu.objects.iter().map(|object| object.address).collect(); assert_eq!(addresses, (first..first + 16).collect::<Vec<u32>>()); assert!(asdu.undecoded.is_empty()); } } }
An APDU cut by the segment
The crate is stateless and does not reassemble TCP. When the last APDU of a segment announces more bytes than the segment holds, it is decoded on what is left and truncated is set: its APCI is read, its ASDU too if the ASDU header is complete, with the objects that fit; if the header is not, asdu is None, which is not an error. Six bytes of APCI remain the minimum. The next segment, which starts in the middle of the APDU, is another matter: the decoder expects 0x68 at its first byte and does not look further for one, so that segment is not IEC 104. The corpus holds no cut APDU (the golden test counts zero), so the example cuts a real segment itself (tested):
#![allow(unused)] fn main() { #[test] fn iec104_an_apdu_cut_by_the_segment_is_decoded_as_far_as_it_goes() { // The payload of the same frame, cut where a TCP segment could end. let raw = hex::decode(IEC104_SEQUENCE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); // 51 bytes: the first APDU (31 bytes), then the APCI, the ASDU header, // the address and five of the sixteen elements of the second. let packet = Iec104Packet::try_from(&payload[..51]).unwrap(); assert!(packet.truncated); let second = packet.apdus[1].asdu.as_ref().unwrap(); assert_eq!((second.count, second.objects.len()), (16, 5)); assert_eq!(second.objects[4].address, 20); // 40 bytes: the APCI of the second APDU is there, but only half of its // ASDU header. The APDU is kept, without an ASDU. let packet = Iec104Packet::try_from(&payload[..40]).unwrap(); assert!(packet.truncated); assert!(matches!( packet.apdus[1].format, ApciFormat::Information { send_sequence: 2, .. } )); assert!(packet.apdus[1].asdu.is_none()); // 35 bytes: not even the six bytes of APCI of the second APDU. assert_eq!( Iec104Packet::try_from(&payload[..35]), Err(Iec104ParseError::Truncated { expected: 6, actual: 4 }) ); // And what the next segment would start with, the rest of an APDU, is // not IEC 104: there is no resynchronization. assert!(matches!( Iec104Packet::try_from(&payload[51..]), Err(Iec104ParseError::InvalidStartByte(_)) )); } }
Validations
All of them are Iec104ParseError:
| Error | When |
|---|---|
Truncated { expected, actual } | fewer than the 6 bytes of an APCI left, an empty payload included |
InvalidStartByte(u8) | an APDU that does not start with 0x68 |
InvalidLength(u8) | a length outside 4..=253 |
ControlOnlyFormat { format, length } | an S or U APDU whose length is not 4 |
InvalidUnnumberedFunction(u8) | a U-format control byte that is not exactly one of the six functions |
AsduTooShort(usize) | a complete I-format APDU with less than the 6 bytes of an ASDU header |
EmptyAsdu(u8) | an ASDU that announces no object |
A refused segment is not labelled, even on port 2404: it goes on to the rest of the table and usually comes out "Unknown", with nothing in corrupted.
Oracle: 373 segments against tshark
The golden test tests/iec104_golden.rs runs the five captures of pcaps_exemple/protocols/iec104/. It compares every TCP segment that has a payload with tshark 4.6.6 without TCP reassembly (tools/iec104_oracle.sh, frozen in tests/data/iec104_tshark_oracle.tsv), APDU by APDU: length, format, U function, N(S) and N(R), and for each ASDU the type, SQ, count, cause, originator and common addresses and the address of every object.
| What the test counts | Number |
|---|---|
segments with a payload, all on port 2404, all labelled "IEC 104" | 374 |
| of them, compared with tshark | 373 |
| APDUs | 448 |
| ASDUs, of 27 types | 301 |
| information objects | 668 |
| ASDUs in sequence | 46 |
| cut APDUs | 0 |
The segment that is not compared is a retransmission. tshark does not dissect it; the crate, which has no notion of retransmission, decodes it like the others.
A second test takes frame 9 of wireshark_iec104.pcap off port 2404 and back through Decode As. It also refuses three single-byte alterations of the frame: the start byte, a length below 4, a count of zero.
The fuzz target parse_iec104 runs nightly on the same parser. The APDUs must tile the input, the last one possibly cut; every element must borrow the input; and the objects of an ASDU in sequence must be numbered one after the other.
| Capture | Frames | Content | Origin |
|---|---|---|---|
wireshark_iec104.pcap | 105 | a complete session (2013): TESTFR, STARTDT, general interrogation, end of initialization, monitoring types 1, 3, 5, 7, 9, 11 and 13, their CP56Time2a forms 30 to 36, commands 45 to 51 | Wireshark wiki |
wireshark_IEC104_SQ.pcapng | 1 | one segment of four M_SP_NA_1 in sequence, sixteen points each | Wireshark wiki |
iti_090813_diverse.pcap | 173 | a master and a station on one machine (2009), commands with a CP56Time2a time tag (types 58, 59, 61, 63) | ITI ICS-Security-Tools |
iti_JavaRMI_and_IEC_Misc.pcap | 357 | two masters and one station (2008): repeated interrogations, answers in sequence, one retransmission | ITI ICS-Security-Tools |
ndpi_IEC104.pcap | 15 | time-tagged floating-point measurements (M_ME_TF_1, type 36) and S acknowledgements (2011) | nDPI test corpus |
The licences, GPL for the wiki, LGPL-3.0 for nDPI and CC-BY-4.0 for ITI, are in the folder's SOURCE.md. A second capture of the nDPI corpus is left out: it mixes a real session with fabricated segments, and a mixed capture cannot be sorted.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- Element values are raw: no measured value, quality descriptor or time tag is interpreted, and causes of transmission are numbers.
- No link state: no tracking of the sequence numbers, of the acknowledgement windows or of the timers; one segment at a time.
- No reassembly of TCP, and no resynchronization inside a segment that starts in the middle of an APDU.
- The field sizes are the -104 parameters, fixed: a two-byte cause, a two-byte common address, a three-byte object address.
- File transfer segments (type 125) and type 127 stay in
undecoded.
IKE
Internet Key Exchange, in both its versions: IKEv1, RFC 2409 on the ISAKMP framework of RFC 2408, and IKEv2, RFC 7296. Added in 11.6.0 (#124) with its companion ESP, as part of the defense lot (#125), which this release completes: on a defense network, the "black" side of the IP encryptors is made of IKE and ESP, and labelling IKE and exposing the SPIs is enough to map who negotiates with whom. The decoder reads the 28-byte header and the chain of top-level payloads without entering them; what is encrypted stays bytes. The module is packet_parser::parse::application::protocols::ike, the error type IkeParseError is in packet_parser::errors::application::ike.
On UDP 500 and 4500, by port
IKE travels over UDP: port 500 (IANA isakmp), and port 4500 (IANA ipsec-nat-t) behind a NAT (RFC 3948), or because the implementation chose that port. The rule of the dispatch table is port-guarded, 500 or 4500 on either side:
#![allow(unused)] fn main() { port_rule(ApplicationProtocol::Ike, Guard::Udp, is_ike_udp_port, ProbeId::Ike), // 500, 4500 }
There is no blind probe: a 28-byte header with a plausible version and length is not a signature strong enough to try on every datagram. The probe is IkePacket::from_udp, run on the whole datagram, as every probe but the four text ones since 11.7.0: the header's length must cover the message exactly. The rule sits among the port rules, after PostgreSQL's and right before the two other rules of port 4500, ESP and NAT-keepalive; the WireGuard rule of UDP 51820 comes later, so that an IKE packet whose peer drew 51820 as its ephemeral port keeps its label.
One side is enough. In ipsec_isakmp_esp.pcap, a client behind a NAT, 192.168.2.100, talks to nine gateways from ports 10500, 14500 and a few ephemeral ones: only the gateway's side is 500 or 4500. The capture's 279 IKE_SA_INIT messages are on UDP 500, its 240 IKE_AUTH and INFORMATIONAL messages on UDP 4500, with its 315 ESP packets.
IKE on another port is declared with ParseConfig::decode_as(port, DecodeAsProtocol::Ike) (Decode As), one of the DecodeAsProtocol variants added in 11.6.0: same probe, same transport guard, and the content still decides (tested):
#![allow(unused)] fn main() { #[test] fn ike_on_another_port_needs_decode_as() { let mut raw = hex::decode(NAT_T_IKE_HEX).unwrap(); move_to_port_4501(&mut raw); // The same bytes, on a port the table does not guard: no IKE. assert_eq!(label(&raw, &ParseConfig::new()), Some("Unknown")); // Declared, the port is guarded too... let config = ParseConfig::new().decode_as(4501, DecodeAsProtocol::Ike); assert_eq!(label(&raw, &config), Some("IKE")); // ...and the content still decides: one bit off in the IKE length // (bytes 70 to 73 of the frame, 76 becomes 77), and no label. raw[73] ^= 0x01; assert_eq!(label(&raw, &config), Some("Unknown")); } }
Being port-guarded, IKE is not tried by classify_payload when it is given no port (None, None): a port rule needs a port to check.
UDP 4500: three things on one port
RFC 3948 §2 shares port 4500 between three kinds of datagrams, and UdpEncapsulation::classify tells them apart:
#![allow(unused)] fn main() { #[non_exhaustive] pub enum UdpEncapsulation<'a> { Ike(&'a [u8]), // the non-ESP marker, then an IKE message: the bytes after the marker Esp(&'a [u8]), // an ESP packet, non-zero SPI first: the whole datagram Keepalive, // NAT-keepalive: a single 0xFF byte } }
classify reads the UDP payload in this order, and the first matching row decides:
| UDP payload | classify |
|---|---|
exactly one byte, 0xFF (§2.3) | Keepalive |
| four zero bytes, the non-ESP marker (§2.2), then at least one byte | Ike(rest), the bytes after the marker, not yet decoded |
| the marker alone, or fewer than 8 bytes | Err(InvalidUdpEncapsulation { length }) |
| anything else: a non-zero SPI and a sequence number (§2.1) | Esp(payload), the whole datagram |
The marker sits where an ESP packet has its SPI, and an SPI of zero is reserved and never sent (RFC 4303 §2.1): no ESP packet starts with it. Port 4500 has three rules, in this order:
#![allow(unused)] fn main() { port_rule(ApplicationProtocol::Ike, Guard::Udp, is_ike_udp_port, ProbeId::Ike), // 500, 4500 port_rule(ApplicationProtocol::Esp, Guard::Udp, is_nat_t_udp_port, ProbeId::EspNatT), // 4500 port_rule(ApplicationProtocol::NatKeepalive, Guard::Udp, is_nat_t_udp_port, ProbeId::NatKeepalive), // 4500 }
The IKE probe does not go through classify: IkePacket::from_udp tries the bare message first, as on port 500, and if that fails while the marker is there with something after it, it decodes what follows the marker. A bare IKE message on 4500 is therefore accepted too. The other two rules give the labels "ESP" and "NAT-keepalive", described on the ESP page; UDP 500 carries neither.
Frame 42 of ipsec_isakmp_esp.pcap is an INFORMATIONAL behind the marker. Read bare, the marker becomes the first half of an initiator SPI, every field slides by four bytes, and the length read is 0 (tested):
#![allow(unused)] fn main() { #[test] fn ike_on_udp_4500_follows_the_non_esp_marker() { let raw = hex::decode(NAT_T_IKE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let transport = flow.transport.as_ref().unwrap(); assert_eq!( (transport.source_port, transport.destination_port), (Some(4500), Some(14500)) ); assert_eq!( flow.application.as_ref().unwrap().protocol.label(), "IKE" ); let payload = transport.payload.unwrap(); assert_eq!(&payload[..4], [0, 0, 0, 0]); // the non-ESP marker // Read bare, the marker becomes half of an initiator SPI, every field // slides by four bytes, and the length read is 0. assert_eq!( IkePacket::try_from(payload), Err(IkeParseError::LengthMismatch { declared: 0, actual: 80 }) ); let Ok(UdpEncapsulation::Ike(message)) = UdpEncapsulation::classify(payload) else { panic!("expected the non-ESP marker"); }; assert_eq!(message.len(), 76); // from_udp tries the bare message, then what follows the marker. let ike = IkePacket::from_udp(payload).unwrap(); assert_eq!(ike.header.initiator_spi, 0xde64_8338_c613_aa68); assert_eq!(ike.header.exchange(), Some(ExchangeType::Informational)); assert_eq!(ike.header.length, 76); assert_eq!(ike.payload_types().collect::<Vec<_>>(), [46]); } }
The header
#![allow(unused)] fn main() { #[non_exhaustive] pub struct IkeHeader { pub initiator_spi: u64, // IKEv1: the initiator's cookie pub responder_spi: u64, // zero in the first message of an initial exchange pub next_payload: u8, // type of the first payload pub version: u8, // raw: major version on the high nibble, minor on the low pub exchange_type: u8, // raw; exchange() names it pub flags: u8, // raw; one accessor per flag, by version pub message_id: u32, pub length: u32, // the whole message, header included } }
ISAKMP and IKEv2 share the layout (RFC 2408 §3.1, RFC 7296 §3.1), big-endian:
| Bytes | Field | Note |
|---|---|---|
| 0–7 | initiator_spi | never zero in IKEv2 (ZeroInitiatorSpi) |
| 8–15 | responder_spi | |
| 16 | next_payload | in an IKEv1 message under the E flag, the first payload under the encryption |
| 17 | version | major_version(), 1 or 2 (UnsupportedVersion otherwise), and minor_version(), not checked |
| 18 | exchange_type | exchange() returns an Option<ExchangeType> |
| 19 | flags | read by the accessors below |
| 20–23 | message_id | |
| 24–27 | length | must equal the size of the message decoded (LengthMismatch) |
The flags byte is the same in both versions, its bits are not. Each accessor returns false for the other version: IKEv2 encrypts with a payload, not a flag.
| Accessor | Version | Bit | Meaning |
|---|---|---|---|
encryption_flag() | IKEv1 | E 0x01 | the payloads are encrypted |
commit_flag() | IKEv1 | C 0x02 | the peer must wait for the sender's CONNECTED notification before using the SA |
authentication_only_flag() | IKEv1 | A 0x04 | authentication only, no encryption |
initiator_flag() | IKEv2 | I 0x08 | sent by the initiator of the IKE SA |
version_flag() | IKEv2 | V 0x10 | the sender can speak a higher major version |
response_flag() | IKEv2 | R 0x20 | a response |
ExchangeType names the code according to the major version (RFC 2408, RFC 2409 for quick mode and new group mode, RFC 7296 and the IANA registry IKEv2 Exchange Types). Since 11.7.0 (#189), every IKEv2 code the registry assigns, 34 to 44, has a variant: GsaInbandRekey names 42, the GSA_INBAND_REKEY of G-IKEv2 (RFC 9838 §2.4.2), which tshark 4.6.6 still shows as "Unassigned". In IKEv1, Transaction names code 6, the Transaction exchange of mode-config (draft-dukes-ike-mode-cfg-02), as tshark does: the registry lists 6 to 31 as "ISAKMP Future Use", and the draft was never standardized, like payload 14 below. Any other code is None, and the message is decoded all the same.
ExchangeType | IKEv1 | IKEv2 |
|---|---|---|
Base | 1 | — |
IdentityProtection (main mode) | 2 | — |
AuthenticationOnly | 3 | — |
Aggressive | 4 | — |
Informational | 5 | 37 |
Transaction (mode-config, 11.7.0) | 6 | — |
QuickMode | 32 | — |
NewGroupMode | 33 | — |
IkeSaInit | — | 34 |
IkeAuth | — | 35 |
CreateChildSa | — | 36 |
IkeSessionResume | — | 38 |
GsaAuth, GsaRegistration, GsaRekey | — | 39, 40, 41 |
GsaInbandRekey (11.7.0) | — | 42 |
IkeIntermediate | — | 43 |
IkeFollowupKe | — | 44 |
The first message of the site-to-site VPN of the corpus, an IKE_SA_INIT on UDP 500 (tested):
#![allow(unused)] fn main() { #[test] fn an_ike_sa_init_on_udp_500() { let raw = hex::decode(IKEV2_SA_INIT_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); // Port 500 and a message whose length covers the datagram: "IKE". assert_eq!( flow.application.as_ref().unwrap().protocol.label(), "IKE" ); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let ike = IkePacket::from_udp(payload).unwrap(); let header = ike.header; assert_eq!(header.initiator_spi, 0x62f9_4c98_8771_5a34); assert_eq!(header.responder_spi, 0); // not chosen yet assert_eq!((header.major_version(), header.minor_version()), (2, 0)); assert_eq!(header.exchange(), Some(ExchangeType::IkeSaInit)); assert!(header.initiator_flag() && !header.response_flag()); assert_eq!((header.message_id, header.length), (0, 374)); // The top-level chain: SA, KE, Nonce, two Vendor IDs, three // Notifications, a Vendor ID; the last one says "no next payload". assert_eq!( ike.payload_types().collect::<Vec<_>>(), [33, 34, 40, 43, 43, 41, 41, 41, 43] ); assert_eq!(ike.payloads[0].kind, Some(PayloadType::SecurityAssociation)); assert_eq!(ike.payloads[2].kind, Some(PayloadType::Nonce)); assert_eq!(ike.payloads[3].length, 23); // generic header included assert_eq!(ike.payloads[3].body, b"CISCO-DELETE-REASON"); assert_eq!(ike.payloads[8].next_payload, 0); assert!(ike.payloads.iter().all(|payload| !payload.critical)); assert_eq!(ike.encrypted_body, None); } }
The payload chain
After the header come the payloads, each with a 4-byte generic header (RFC 7296 §3.2, RFC 2408 §3.2):
#![allow(unused)] fn main() { #[non_exhaustive] pub struct IkePayload<'a> { pub payload_type: u8, // raw code, as the previous payload (or the header) names it pub kind: Option<PayloadType>, // the code named, by the version of the message pub next_payload: u8, // 0 for the last one; in an IKEv2 SK, the first payload under the encryption pub critical: bool, // IKEv2 only: always false in IKEv1, where the byte is reserved pub length: u16, // declared, generic header included pub body: &'a [u8], // the bytes after the generic header, borrowed } }
| Bytes | Field |
|---|---|
| 0 | next_payload |
| 1 | critical bit 0x80, then reserved |
| 2–3 | length |
4 to length − 1 | body |
A payload does not carry its own type: the header's next_payload names the first one, and each payload names the next. IkePacket::payloads keeps them in message order, and payload_types() iterates their raw codes. The walk checks each length, and the chain must end with the message:
- a length below the 4 bytes of the generic header is
InvalidPayloadLength { payload_type, length }, a length beyond what remains isPayloadOverflow { payload_type, needed, available }; - the chain ends on a
next_payloadof 0, and bytes left after it areUnexpectedTrailingBytes { trailing }; - the chain also ends with the message when the last payload announces another one, as tshark reads it: frame 192 of
ipsec_isakmp_esp.pcapis an IKE_AUTH whose only payload, of the unassigned type 127 and 784 bytes, announces a 35. One to three bytes left for an announced payload cannot hold its header, though:PayloadOverflowwithneeded: 4.
Only the top level is walked: Proposal and Transform live inside a Security Association, and no body is decoded. payloads is the decoder's one allocation; the bodies borrow the packet. PayloadType names the codes according to the version: for IKEv1, RFC 2408, RFC 3947 for NAT-T, RFC 3547 and RFC 6407 for GDOI, and the IANA registry Next Payload Types; for IKEv2, RFC 7296 and the IANA registry IKEv2 Payload Types. An unknown code, such as the unassigned 127, is None and its payload is kept like the others.
PayloadType | IKEv1 | IKEv2 |
|---|---|---|
SecurityAssociation | 1 | 33 |
Proposal, Transform | 2, 3 | — |
KeyExchange | 4 | 34 |
Identification | 5 | — |
IdentificationInitiator, IdentificationResponder | — | 35, 36 |
Certificate, CertificateRequest | 6, 7 | 37, 38 |
Hash, Signature | 8, 9 | — |
Authentication | — | 39 |
Nonce | 10 | 40 |
Notification | 11 | 41 |
Delete | 12 | 42 |
VendorId | 13 | 43 |
Attributes (mode-config) | 14 | — |
SaKek, SaTek (GDOI, 11.7.0) | 15, 16 | — |
KeyDownload | 17 (GDOI, 11.7.0) | 52 |
SequenceNumber, ProofOfPossession (GDOI, 11.7.0) | 18, 19 | — |
NatDiscovery (NatDetection until 12.0.0) | 20 (RFC 3947); 130 (drafts) | — |
NatOriginalAddress | 21 (RFC 3947); 131 (drafts) | — |
GroupAssociatedPolicy (GDOI, 11.7.0) | 22 | — |
TrafficSelectorInitiator, TrafficSelectorResponder | — | 44, 45 |
Encrypted (SK) | — | 46 |
Configuration | — | 47 |
ExtensibleAuthentication | — | 48 |
GenericSecurePasswordMethod | — | 49 |
GroupIdentification, GroupSecurityAssociation | — | 50, 51 |
EncryptedFragment (SKF, RFC 7383) | — | 53 |
PuzzleSolution | — | 54 |
Payload 14, the attributes of mode-config, comes from a draft that was never standardized: the IANA registry marks it "Reserved, not to be used". Codes 130 and 131 are those of the NAT-T drafts draft-ietf-ipsec-nat-t-ike-00 to -03.
In IKEv1, codes 15 and 16 changed meaning in 11.7.0 (#189).
| Code | 11.6.0 | Since 11.7.0 | Registered by |
|---|---|---|---|
| 15 | NatDetection, renamed NatDiscovery in 12.0.0 | SaKek, SA KEK (SAK) | RFC 3547, GDOI |
| 16 | NatOriginalAddress | SaTek, SA TEK (SAT) | RFC 3547, GDOI |
| 17 to 19, 22 | None | the other GDOI types | RFC 3547, GDOI |
11.6.0 followed the drafts draft-ietf-ipsec-nat-t-ike-04 to -08, which used 15 and 16 without registering them. The Next Payload Types registry gives them to GDOI since RFC 3547, and RFC 3947 took 20 and 21 for NAT-T; NatDiscovery is the name RFC 3947 uses. PayloadType::from_code(1, 15) now returns Some(SaKek) and from_code(1, 16) Some(SaTek), as tshark ("SA KEK Payload", "SA TEK Payload"), libreswan and strongSwan read them.
A caller that matches on NatDiscovery or NatOriginalAddress no longer sees 15 or 16, including from a peer that still follows those drafts.
None of the 1 254 ISAKMP frames of the crate's corpus carries these codes in clear. Apart from a peer that follows the drafts, a GDOI type appears in clear at the top level only in the header of an encrypted message, whose next_payload names the first payload under the encryption: a GROUPKEY-PUSH announces a Sequence Number.
The codes of both tables, as from_code reads them (tested):
#![allow(unused)] fn main() { #[test] fn exchange_and_payload_codes_follow_the_iana_registries() { // The first argument is the major version, 1 or 2. assert_eq!(ExchangeType::from_code(2, 42), Some(ExchangeType::GsaInbandRekey)); assert_eq!(ExchangeType::from_code(1, 6), Some(ExchangeType::Transaction)); assert_eq!(ExchangeType::from_code(1, 7), None); // ISAKMP Future Use assert_eq!(ExchangeType::from_code(2, 6), None); // IKEv1 only // IKEv1 15 and 16 are GDOI's SA KEK and SA TEK, no longer NAT-T. assert_eq!(PayloadType::from_code(1, 15), Some(PayloadType::SaKek)); assert_eq!(PayloadType::from_code(1, 16), Some(PayloadType::SaTek)); // NAT-D and NAT-OA: 20 and 21 of RFC 3947, 130 and 131 of the drafts. for code in [20, 130] { assert_eq!(PayloadType::from_code(1, code), Some(PayloadType::NatDiscovery)); } for code in [21, 131] { assert_eq!(PayloadType::from_code(1, code), Some(PayloadType::NatOriginalAddress)); } // The other GDOI types; Key Download has a code in each version. assert_eq!(PayloadType::from_code(1, 17), Some(PayloadType::KeyDownload)); assert_eq!(PayloadType::from_code(2, 52), Some(PayloadType::KeyDownload)); assert_eq!(PayloadType::from_code(1, 18), Some(PayloadType::SequenceNumber)); assert_eq!(PayloadType::from_code(1, 19), Some(PayloadType::ProofOfPossession)); assert_eq!(PayloadType::from_code(1, 22), Some(PayloadType::GroupAssociatedPolicy)); // A code is read by the version of the message: 15 means nothing in IKEv2. assert_eq!(PayloadType::from_code(2, 15), None); assert_eq!(PayloadType::from_code(2, 127), None); // unassigned } }
What is encrypted
#![allow(unused)] fn main() { #[non_exhaustive] pub struct IkePacket<'a> { pub header: IkeHeader, pub payloads: Vec<IkePayload<'a>>, // top level, in message order pub encrypted_body: Option<&'a [u8]>, // the protected bytes, as they are } }
The two versions encrypt differently, and encrypted_body covers both:
- IKEv1 sets the E flag, and everything after the header is encrypted.
payloadsis empty,encrypted_bodyis the rest of the message, all of it encrypted, andheader.next_payloadnames the first payload under the encryption. In the main mode capture of the corpus, the eight messages after the key exchange, frames 5 to 12, are sent that way. - IKEv2 encrypts in a payload, SK (46), or SKF (53) for a fragment, which must be the last of the message (RFC 7296 §3.14). The walk stops on it, so a byte after it is
UnexpectedTrailingBytes. It is the last entry ofpayloadsand its body isencrypted_body; itsnext_payloadnames the first payload under the encryption, not a top-level one. Not every byte of that body is encrypted: it holds the IV in clear, then the encrypted payloads with their padding, then the integrity checksum data, in clear too (RFC 7296 §3.14), and an SKF puts its fragment number and total fragments before the IV (RFC 7383 §2.5). The crate does not split them; their sizes depend on the negotiated algorithms. In the corpus, 241 IKEv2 messages end with an SK: every IKE_AUTH and every INFORMATIONAL, except frame 192 and its payload of type 127.
The IKE_AUTH response of the VPN, then the first and fifth messages of an IKEv1 main mode (tested):
#![allow(unused)] fn main() { #[test] fn what_is_encrypted_stays_bytes() { // IKEv2, frame 4: the IKE_AUTH response is a single SK payload. let raw = hex::decode(IKEV2_IKE_AUTH_RESPONSE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let auth = IkePacket::from_udp(payload).unwrap(); assert_eq!(auth.header.initiator_spi, 0x62f9_4c98_8771_5a34); // same IKE SA assert_eq!(auth.header.responder_spi, 0xf055_34ee_f373_dc1b); assert_eq!(auth.header.exchange(), Some(ExchangeType::IkeAuth)); assert!(auth.header.response_flag()); assert_eq!(auth.payload_types().collect::<Vec<_>>(), [46]); let sk = &auth.payloads[0]; assert_eq!(sk.kind, Some(PayloadType::Encrypted)); assert_eq!(sk.next_payload, 43); // the first payload under the encryption assert_eq!(sk.length, 201); assert_eq!(auth.encrypted_body, Some(sk.body)); assert_eq!(sk.body.len(), 197); // IKEv1, frames 1 and 5 of the main mode: in clear, then under the E flag. let raw = hex::decode(IKEV1_MAIN_MODE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let first = IkePacket::from_udp(payload).unwrap(); assert_eq!(first.header.major_version(), 1); assert_eq!( first.header.exchange(), Some(ExchangeType::IdentityProtection) ); assert_eq!(first.payload_types().collect::<Vec<_>>(), [1, 13, 13]); // SA, two VIDs let raw = hex::decode(IKEV1_ENCRYPTED_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let fifth = IkePacket::from_udp(payload).unwrap(); assert!(fifth.header.encryption_flag()); assert_eq!(fifth.header.next_payload, 5); // Identification, under the encryption assert!(fifth.payloads.is_empty()); assert_eq!(fifth.encrypted_body.map(<[u8]>::len), Some(76 - 28)); } }
Validations
All of them are IkeParseError, checked in this order:
| Error | When |
|---|---|
Truncated { expected, actual } | fewer than the 28 bytes of the header |
UnsupportedVersion(u8) | a major version other than 1 or 2 |
ZeroInitiatorSpi | IKEv2 with an initiator SPI of zero |
LengthMismatch { declared, actual } | the header's length is not the size of the message |
InvalidPayloadLength { payload_type, length } | a payload declares less than its 4-byte generic header |
PayloadOverflow { payload_type, needed, available } | a payload runs past the message, or one to three bytes are left for an announced payload |
UnexpectedTrailingBytes { trailing } | bytes after the last payload, or after an IKEv2 SK or SKF |
InvalidUdpEncapsulation { length } | UdpEncapsulation::classify only: neither a keepalive, nor the marker with bytes after it, nor 8 bytes for an ESP header |
A failure is not a corruption. The port is a hint: when the probe fails, the datagram goes on to the rules that follow, and nothing is reported in corrupted.
Oracle: 535 messages, field by field
The golden test tests/ipsec_golden.rs runs the three captures of pcaps_exemple/protocols/ipsec/, 858 frames, and compares every one with tshark 4.6.6, frozen in tests/data/ipsec_tshark_oracle.tsv by tools/ipsec_oracle.sh.
- For each IKE message: both SPIs, the version, the exchange type, the flags, the message ID, the length, and the top-level chain with the length of each payload. tshark's Proposal and Transform, nested in a Security Association, are left out.
- For each ESP packet: the SPI and the sequence number (ESP).
No Decode As is needed: every IKE frame has 500 or 4500 on one side.
| IKE messages | Number | Of which |
|---|---|---|
| IKEv1 | 12 | 6 main mode, 3 quick mode, 3 informational |
| IKEv2 | 523 | 281 IKE_SA_INIT, 224 IKE_AUTH, 18 INFORMATIONAL |
| with an encrypted body | 249 | 8 IKEv1, 241 IKEv2 |
| all | 535 |
A second test moves frame 42 and frame 11 of the nDPI capture, IKE behind the marker and ESP, to port 4501, where they become "Unknown", and declares them back with Decode As.
| Capture | Frames | Content | Origin |
|---|---|---|---|
attachment_ikev1_main_mode.pcap | 12 | IKEv1 on UDP 500: main mode, quick mode, informational | Wireshark wiki |
ikev2_s2s_ipsec_vpn_aes_gcm.pcapng | 12 | a site-to-site VPN: IKEv2 on UDP 500 (4), then native ESP (8) | Wireshark wiki |
ipsec_isakmp_esp.pcap | 834 | a client behind a NAT: IKEv2 on UDP 500 (279), IKEv2 (240) and ESP (315) on UDP 4500 | nDPI test corpus |
In the golden histogram of pcaps_exemple/protocols/ (tests/golden_pcaps.rs), "IKE" went from 0 to 535 and "ESP" from 0 to 315 with 11.6.0, all 850 frames taken from "Unknown". The-Ultimate-PCAP.pcapng, at the root of pcaps_exemple/, is read by neither test; a run of 11.6.0 over it labels 719 frames "IKE", as many as the ISAKMP frames tshark counts there. The fuzz target parse_ipsec runs nightly on IkePacket, UdpEncapsulation::classify and EspPacket.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- Payload contents: proposals and transforms, key exchange data, nonces, identities, certificates, notifications and vendor IDs are bytes in
body. A vendor ID is recognizable by its bytes, theCISCO-DELETE-REASONof the example, not named. - Decryption: none, in either version;
encrypted_bodyis the bytes as they are, with the clear IV and integrity data of an IKEv2 SK or SKF. - No state: no pairing of a request with its response, no SA table, no link between an IKE SA and the ESP SPIs it negotiates. One message at a time, like the rest of the crate.
- IKEv2 fragments (SKF) are decoded one message at a time, never reassembled; an IKE message split by IP fragmentation has no transport layer, as everywhere in the crate.
- IKE over TCP is not recognized: the rule is
Guard::Udp.
Java RMI
Java RMI lets a JVM call a method of an object that lives in another JVM. Its wire protocol is JRMP, chapter 10 of the Java RMI Specification, "RMI Wire Protocol". It runs over TCP. The decoder was added in 13.0.0 (#313, PR #314). The module is packet_parser::parse::application::protocols::java_rmi, the errors are in packet_parser::errors::application::java_rmi, and the label is "Java RMI".
A client opens a connection with a stream header: JRMI, a version, a protocol. Then each message starts with a type byte. The client sends Calls, the server answers with Returns. Ping and PingAck check an idle connection. A DgcAck acknowledges the remote references that a Return carried. A Call and a Return carry a Java serialization stream: the decoder reads the call header and the return header, and leaves the arguments and the value as bytes.
Detection: TCP 1099, then any TCP port
The registry listens on TCP 1099, the IANA port rmiregistry. The objects it hands out, and the JMX connectors, listen on a port the application picks. So Java RMI has two rules and a Decode As variant:
| Where | Rule | Probe | Accepts |
|---|---|---|---|
| TCP 1099, on either side | port rule 35 | ProbeId::JavaRmi | any message that JavaRmiPacket::try_from accepts |
a port declared with ParseConfig::decode_as(port, DecodeAsProtocol::JavaRmi) | tried before the table | ProbeId::JavaRmi | the same |
| any other TCP port | blind rule 67 | ProbeId::JavaRmiBlind | a stream header, a Call or a Return |
Rule 35 sits among the port rules of the table, after IEC 104 and before PostgreSQL. Rule 67 sits in the blind cascade, after GIOP and before DHCP. Both probes read the whole payload. All three routes keep the TCP guard: the same bytes over UDP are never "Java RMI".
Why two probes: three messages carry a signature, the others do not.
- The stream header is
JRMI, then one of two versions and one of three protocols. - A Call or a Return is its type byte, then
AC ED 00 05, the magic and the version of a Java serialization stream, then a block marker and a block long enough for its header. The source counts at least 48 fixed bits. - Ping, PingAck and ProtocolNotSupported are one byte.
- A DgcAck is a type byte and fourteen free bytes, a UID.
- A ProtocolAck is a type byte, a length, a hostname and a port.
JavaRmiPacket::is_self_identifying() is true for the stream header, the Call and the Return, and the blind probe asks for it. The other five messages need TCP 1099 or a declared port. DecodeAsProtocol::JavaRmi, new in 13.0.0 and the 30th of the 31 variants, resolves to the label Java RMI, the guard Tcp and the probe of rule 35.
A Ping on 1099 and off it, then a declared port (tested):
#![allow(unused)] fn main() { #[test] fn a_one_byte_message_needs_port_1099_or_a_decode_as() { // Frame 36: a Ping on the registry connection, 36568 -> 1099. let raw = hex::decode(REGISTRY_PING_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(payload(&flow), [0x52]); assert_eq!(JavaRmiPacket::try_from(payload(&flow)), Ok(JavaRmiPacket::Ping)); assert_eq!(label(&flow), Some("Java RMI")); // Frame 54: the same byte on the object's connection, 53372 -> 50050. // One byte proves nothing: the blind rule leaves it. let raw = hex::decode(STATION_PING_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(payload(&flow), [0x52]); assert_eq!(label(&flow), Some("Unknown")); // A declared port gets the probe of the 1099 rule. let config = ParseConfig::new().decode_as(50050, DecodeAsProtocol::JavaRmi); let flow = parse_with(LinkType::ETHERNET, &raw, &config).unwrap(); assert_eq!(label(&flow), Some("Java RMI")); // Frame 45: the object's ProtocolAck, 50050 -> 53372. A type byte and // free fields: off 1099, only the declared port labels it. let raw = hex::decode(STATION_PROTOCOL_ACK_HEX).unwrap(); assert_eq!(label(&parse(LinkType::ETHERNET, &raw).unwrap()), Some("Unknown")); let flow = parse_with(LinkType::ETHERNET, &raw, &config).unwrap(); assert_eq!(label(&flow), Some("Java RMI")); let packet = JavaRmiPacket::try_from(payload(&flow)).unwrap(); assert!(!packet.is_self_identifying()); let JavaRmiPacket::ProtocolAck(endpoint) = packet else { panic!("expected a ProtocolAck, got {packet:?}"); }; // The client as the server sees it: its address and its port. assert_eq!(endpoint.hostname_str(), Some("127.0.0.1")); assert_eq!(endpoint.port, 53372); } }
On the capture of the corpus, a registry on 1099, an exported object on 50050 and a JMX connector on 50051, the routes give:
| Server port | Segments with a payload | parse: "Java RMI" | parse_with, 50050 and 50051 declared |
|---|---|---|---|
| 1099, the registry | 33 | 29 | 29 |
50050, the Station object | 43 | 23 | 40 |
| 50051, the JMX connector | 160 | 91 | 157 |
| total | 236 | 143 | 226 |
Off 1099, parse labels the 114 stream headers, Calls and Returns, and leaves the Pings, PingAcks, DgcAck and ProtocolAcks "Unknown". Ten segments stay "Unknown" on every route: the nine EndpointIdentifiers and one refused header (below).
The messages
| First byte | Message | Sent by | Size in the segment | JavaRmiPacket | Display |
|---|---|---|---|---|---|
0x4a, the J of JRMI | stream header | client | 7 bytes, then messages | Header(JavaRmiHeader) | JRMI, Version: 2, StreamProtocol |
0x4e | ProtocolAck | server | exactly 7 + the hostname | ProtocolAck(JavaRmiEndpoint) | ProtocolAck 127.0.0.1:36556 |
0x4f | ProtocolNotSupported | server | exactly 1 | ProtocolNotSupported | ProtocolNotSupported |
0x50 | Call | client | at least 41 | Call(JavaRmiCall) | Call Registry.list |
0x51 | Return | server | at least 22 | Return(JavaRmiReturn) | ReturnData |
0x52 | Ping | client | exactly 1 | Ping | Ping |
0x53 | PingAck | server | exactly 1 | PingAck | PingAck |
0x54 | DgcAck | client | exactly 15 | DgcAck(JavaRmiUid) | DgcAck |
message_type() gives the first byte back. The decoder reads one message per segment, and the fixed-size ones must fill it exactly.
#![allow(unused)] fn main() { pub enum JavaRmiPacket<'a> { Header(JavaRmiHeader<'a>), ProtocolAck(JavaRmiEndpoint<'a>), ProtocolNotSupported, Call(JavaRmiCall<'a>), Return(JavaRmiReturn<'a>), Ping, PingAck, DgcAck(JavaRmiUid), // the UID of the Return it acknowledges } pub struct JavaRmiHeader<'a> { pub version: u16, // 1 or 2; every JDK since 1.2 sends 2 pub protocol: JavaRmiProtocol, // Stream, SingleOp or Multiplex pub messages: &'a [u8], // what follows the 7 bytes in the segment } pub struct JavaRmiEndpoint<'a> { pub hostname: &'a [u8], // modified UTF-8, written by writeUTF pub port: u16, } pub struct JavaRmiCall<'a> { pub object: JavaRmiObjId, // the remote object called pub operation: i32, // the method number of a 1.1 stub, or -1 pub hash: i64, // the interface hash (1.1 stub) or the method hash pub arguments: &'a [u8], // the rest of the segment, serialized } pub struct JavaRmiReturn<'a> { pub return_type: JavaRmiReturnType, // Normal or Exceptional pub ack_id: JavaRmiUid, // repeated by a DgcAck pub value: &'a [u8], // the rest of the segment, serialized } pub struct JavaRmiObjId { pub object_number: i64, pub space: JavaRmiUid, } pub struct JavaRmiUid { pub unique: i32, pub time: i64, // milliseconds since the Unix epoch pub count: i16, } }
All of them are #[non_exhaustive], as are JavaRmiProtocol, JavaRmiReturnType, JavaRmiWellKnownObject and the error. A match on JavaRmiPacket needs a _ arm.
A session
One connection of the capture, the client on TCP 36568, the registry on 1099:
| Frame | From | Message |
|---|---|---|
| 28 | client | stream header, StreamProtocol |
| 30 | registry | ProtocolAck, 127.0.0.1:36568: the client as the server sees it |
| 32 | client | its EndpointIdentifier: no type byte, not decoded |
| 33 | client | Call Registry.list() |
| 35 | registry | Return: the names station and jmxrmi |
| 36, 37 | client, registry | Ping, PingAck: the client probes the connection before it reuses it |
| 38 | client | Call Registry.lookup("station") |
| 39 | registry | Return: a dynamic proxy, the remote reference to the Station object |
| 51, 52 | client, registry | Ping, PingAck |
| 53 | client | DgcAck: the UID of the Return of frame 39 |
The stream header
| Bytes | Field | Note |
|---|---|---|
| 0–3 | magic | JRMI, 0x4a524d49; otherwise InvalidHeaderMagic |
| 4–5 | version | 1 or 2; otherwise InvalidVersion |
| 6 | protocol | one of the three below; otherwise UnknownProtocol |
| 7… | messages | the rest of the segment |
JavaRmiProtocol | Byte | name() | What follows |
|---|---|---|---|
Stream | 0x4b | StreamProtocol | nothing in the segment; the server answers with a ProtocolAck, and the connection can be reused |
SingleOp | 0x4c | SingleOpProtocol | the Call, in the same segment; no ProtocolAck, one call per connection |
Multiplex | 0x4d | MultiplexProtocol | streams multiplexed on one connection (JDK 1.1); only the header is read |
code() gives the byte back. JavaRmiHeader::message() decodes messages on demand, and returns None when it is empty. Frame 319 of the capture is a SingleOp header followed by Registry.list(), 48 bytes in one segment.
ProtocolAck, DgcAck and the one-byte messages
The ProtocolAck carries the client's address as the server sees it: a type byte, a two-byte length, the hostname, then the port on four bytes. It must fill the segment exactly, otherwise UnexpectedLength. A port above 65 535 is InvalidPort. hostname_str() returns the hostname when it is valid UTF-8.
The DgcAck is the type byte and a UID, 15 bytes. The client sends it after a Return that carried remote references, and repeats that Return's ack_id. Ping, PingAck and ProtocolNotSupported are their type byte alone.
The Call
| Bytes | Field | Note |
|---|---|---|
| 0 | type | 0x50 |
| 1–2 | stream magic | AC ED; otherwise InvalidStreamMagic |
| 3–4 | stream version | 5; otherwise InvalidStreamVersion |
| 5 | block marker | TC_BLOCKDATA 0x77, or TC_BLOCKDATALONG 0x7a; otherwise ExpectedBlockData |
| 6 | block length | at least 34, otherwise BlockTooShort; after 0x7a, four bytes, 6–9 |
| 7–14 | object.object_number | i64 |
| 15–28 | object.space | a UID: unique (i32), time (i64), count (i16) |
| 29–32 | operation | i32 |
| 33–40 | hash | i64 |
| 41… | arguments | the rest of the segment |
After TC_BLOCKDATALONG, the call header starts three bytes later, at byte 10. The block may run past the segment: only the 34 bytes of the header must be there.
Methods with a name
Three objects have a fixed number in the null space, the UID whose three fields are zero. JavaRmiObjId::well_known() names them. well_known_method() also names the method, when the call goes through the 1.1 stub of the object: the hash is then the interface hash, and the operation indexes the methods.
| Object | object_number | Interface hash | Operations, by number |
|---|---|---|---|
Registry | 0 | JAVA_RMI_REGISTRY_INTERFACE_HASH, 0x44154dc9d4e63bdf | 0 bind, 1 list, 2 lookup, 3 rebind, 4 unbind |
Activator | 1 | none in the crate | not named |
Dgc | 2 | JAVA_RMI_DGC_INTERFACE_HASH, 0xf6b6898d8bf28643 | 0 clean, 1 dirty |
Dgc is the distributed garbage collector: a client calls dirty to lease the references it holds, and clean to release them. Display writes the named method, Call Registry.lookup.
A call to the registry, its Return, then a lookup (tested):
#![allow(unused)] fn main() { #[test] fn a_registry_call_names_its_method() { let raw = hex::decode(REGISTRY_LIST_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("Java RMI")); // 36568 -> 1099 let packet = JavaRmiPacket::try_from(payload(&flow)).unwrap(); assert_eq!(packet.to_string(), "Call Registry.list"); let JavaRmiPacket::Call(call) = packet else { panic!("expected a Call, got {packet:?}"); }; // Object 0 in the null space: the registry of any server. assert_eq!(call.object.object_number, 0); assert!(call.object.space.is_zero()); assert_eq!(call.object.well_known(), Some(JavaRmiWellKnownObject::Registry)); // A 1.1 stub: an operation number and the interface hash. assert_eq!(call.operation, 1); assert_eq!(call.hash, JAVA_RMI_REGISTRY_INTERFACE_HASH); assert_eq!( call.well_known_method(), Some((JavaRmiWellKnownObject::Registry, "list")) ); assert!(call.arguments.is_empty()); // list() takes none // Frame 35: the Return. A type and a UID, then the value. let raw = hex::decode(REGISTRY_LIST_RETURN_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("Java RMI")); // 1099 -> 36568 let JavaRmiPacket::Return(ret) = JavaRmiPacket::try_from(payload(&flow)).unwrap() else { panic!("expected a Return"); }; assert_eq!(ret.return_type, JavaRmiReturnType::Normal); assert_eq!(ret.ack_id.unique, 0xbfcb_98ab_u32 as i32); assert_eq!(ret.ack_id.time, 1_794_909_248_603); // 2026-11-17 09:54:08.603 UTC assert_eq!(ret.ack_id.count, 0x8006_u16 as i16); // The value stays serialized: a TC_ARRAY of String, the two names bound. assert_eq!(ret.value[0], 0x75); assert!(ret.value.ends_with(b"\x74\x00\x07station\x74\x00\x06jmxrmi")); // Frame 38: the lookup of the first name. Its argument is a serialized // String: TC_STRING, a two-byte length, the bytes. let raw = hex::decode(REGISTRY_LOOKUP_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let JavaRmiPacket::Call(call) = JavaRmiPacket::try_from(payload(&flow)).unwrap() else { panic!("expected a Call"); }; assert_eq!(call.operation, 2); assert_eq!( call.well_known_method(), Some((JavaRmiWellKnownObject::Registry, "lookup")) ); assert_eq!(call.arguments, b"\x74\x00\x07station"); } }
An exported object has a random number in the space of its JVM. Its 1.2 stub, or its dynamic proxy, sends operation -1, and the hash names the method. The crate keeps that hash as a number: well_known_method() is None, and Display writes Call object … operation -1 hash 0x…. A call to the Station object of the capture, off 1099 (tested):
#![allow(unused)] fn main() { #[test] fn an_application_call_is_named_by_its_hash() { let raw = hex::decode(STATION_ADD_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); // 53372 -> 50050, a port no rule knows: the blind rule takes a Call. assert_eq!(label(&flow), Some("Java RMI")); let packet = JavaRmiPacket::try_from(payload(&flow)).unwrap(); assert!(packet.is_self_identifying()); let JavaRmiPacket::Call(call) = packet else { panic!("expected a Call, got {packet:?}"); }; // An exported object: a random number, in the space of the server's JVM. assert_eq!(call.object.object_number, 0x18ab_9a45_55f8_f98a); assert_eq!(call.object.well_known(), None); // A 1.2 stub: operation -1, and the hash names the method. assert_eq!(call.operation, -1); assert_eq!(call.hash, 0x94a9_af30_6652_c3a6_u64 as i64); assert_eq!(call.well_known_method(), None); assert_eq!( packet.to_string(), "Call object 1777684100513593738 operation -1 hash 0x94a9af306652c3a6" ); // The block is 42 bytes: the 34 of the call header, then two int. assert_eq!(payload(&flow)[6], 42); assert_eq!(call.arguments, [0, 0, 0, 2, 0, 0, 0, 3]); // Frame 61: the Return, 5, in the same block as its header. let raw = hex::decode(STATION_ADD_RETURN_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("Java RMI")); // 50050 -> 53372 let JavaRmiPacket::Return(ret) = JavaRmiPacket::try_from(payload(&flow)).unwrap() else { panic!("expected a Return"); }; assert_eq!(ret.return_type, JavaRmiReturnType::Normal); assert_eq!(ret.value, [0, 0, 0, 5]); // Both UIDs come from the server's JVM: the same unique and time. assert_eq!(ret.ack_id.unique, call.object.space.unique); assert_eq!(ret.ack_id.time, call.object.space.time); } }
The Return
| Bytes | Field | Note |
|---|---|---|
| 0 | type | 0x51 |
| 1–6 | stream header and block | as in a Call; the block is at least 15 bytes |
| 7 | return_type | 1 Normal, 2 Exceptional; otherwise InvalidReturnType |
| 8–21 | ack_id | a UID |
| 22… | value | the rest of the segment: the value, or the exception |
Display writes ReturnData, and ReturnData (exception) for an exceptional Return.
Validations
All of them are JavaRmiError:
| Error | When |
|---|---|
TooShort { expected, actual } | an empty segment; a stream header under 7 bytes; a ProtocolAck under 3; a Call or a Return that stops before the end of its serialization header, its block marker and length, or its call or return header |
UnknownMessageType(u8) | a first byte other than 0x4a and 0x4e to 0x54 |
InvalidHeaderMagic(u32) | a J that does not open JRMI |
InvalidVersion(u16) | a stream header version other than 1 or 2 |
UnknownProtocol(u8) | a protocol other than 0x4b, 0x4c, 0x4d |
UnexpectedLength { message, expected, actual } | a Ping, PingAck or ProtocolNotSupported that is not 1 byte, a DgcAck that is not 15, a ProtocolAck that is not 7 plus its hostname |
InvalidPort(u32) | a ProtocolAck port above 65 535 |
InvalidStreamMagic(u16) | a Call or a Return without AC ED |
InvalidStreamVersion(u16) | a serialization stream version other than 5 |
ExpectedBlockData(u8) | a byte 5 that is neither 0x77 nor 0x7a |
BlockTooShort { expected, actual } | a block shorter than the call header, 34 bytes, or the return header, 15 |
InvalidReturnType(u8) | a return type other than 1 or 2 |
A refused segment is not labelled, even on 1099. It goes on down the table and usually comes out "Unknown". The flow keeps no error: call JavaRmiPacket::try_from to see it. Three frames of the capture (tested):
#![allow(unused)] fn main() { #[test] fn what_the_decoder_refuses() { // Frame 8: the client's EndpointIdentifier, 36556 -> 1099. No type // byte: it starts with the length of the hostname, 9. let raw = hex::decode(CLIENT_ENDPOINT_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(payload(&flow)[..2], [0x00, 0x09]); assert_eq!( JavaRmiPacket::try_from(payload(&flow)), Err(JavaRmiError::UnknownMessageType(0)) ); assert_eq!(label(&flow), Some("Unknown")); // even on 1099 // Frame 329: a stream header with the protocol 0x4e, 58428 -> 1099. let raw = hex::decode(UNKNOWN_PROTOCOL_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(payload(&flow), b"JRMI\x00\x02\x4e"); let error = JavaRmiPacket::try_from(payload(&flow)).unwrap_err(); assert_eq!(error, JavaRmiError::UnknownProtocol(0x4e)); assert_eq!(error.to_string(), "Unknown Java RMI protocol 0x4e"); assert_eq!(label(&flow), Some("Unknown")); // Frame 331: the registry refuses it with one byte, labelled on 1099. let raw = hex::decode(PROTOCOL_NOT_SUPPORTED_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!( JavaRmiPacket::try_from(payload(&flow)), Ok(JavaRmiPacket::ProtocolNotSupported) ); assert_eq!(label(&flow), Some("Java RMI")); } }
Oracle: 236 segments against tshark
The golden test tests/java_rmi_golden.rs reads the 394 frames of pcaps_exemple/protocols/java_rmi/jdk11-loopback.pcap. It compares every segment that has a payload with tshark 4.6.9. tshark dissects RMI on TCP 1099 only: tools/java_rmi_oracle.sh declares 50050 and 50051 with -d tcp.port==…,rmi, and freezes its output in tests/data/java_rmi_tshark_oracle.tsv. Compared: the type of each message, the version and protocol of each stream header, the hostname and port of each ProtocolAck.
| Message | Segments |
|---|---|
| Return, one of them exceptional (frame 69) | 60 |
| Call | 59 |
| Ping | 42 |
| PingAck | 42 |
stream header: 9 StreamProtocol, 1 SingleOpProtocol with its call | 10 |
| ProtocolAck | 9 |
| EndpointIdentifier of the client, refused: no type byte | 9 |
| DgcAck | 3 |
stream header with the unknown protocol 0x4e, refused | 1 |
| ProtocolNotSupported | 1 |
| total | 236 |
tshark reads neither the call header nor the return header. The test checks what the crate reads there against the structure of the session:
| What the crate reads | Number |
|---|---|
registry calls, to TCP 1099, with the registry's interface hash: bind 1, list 2, lookup 2, unbind 1 | 6 |
DGC calls, to ObjID 2, with the DGC's interface hash: dirty 20, clean 2 | 22 |
| application calls: operation -1, no well-known object | 32 |
| exceptional Returns, whose value holds the message of the exception | 1 |
| DgcAcks whose UID is the one of a Return seen before | 3 |
Every Return has a UID of its own. The test also checks each label: "Java RMI" on 1099, or off it for a stream header, a Call or a Return; "Java RMI" everywhere with 50050 and 50051 declared.
| Capture | Frames | Content | Origin |
|---|---|---|---|
jdk11-loopback.pcap | 394 | two OpenJDK 11.0.33 JVMs on the loopback, 20.4 s, 11 TCP connections; a registry on 1099, a Station object on 50050, a JMX connector on 50051; two connections written by hand, the SingleOp call and the unknown protocol | the maintainer's capture, MIT |
tools/java_rmi_capture.sh reproduces it: it compiles tools/java_rmi_capture/JrmpCapture.java, runs the two JVMs and captures the three ports with dumpcap. The JVMs draw UIDs, object numbers and ephemeral ports at random, so each run differs: the tests cite the frames of the committed file. Its SOURCE.md lists what the payloads contain: 127.0.0.1, class names, the strings of the program and the JDK version, nothing of the machine.
A unit test of dispatch/tests.rs replays frames of the same capture through the table. A stream header, a Call and a Return are "Java RMI" on 1099 and on 50050, never on UDP. A Ping, a PingAck and a DgcAck are "Java RMI" on 1099, "Unknown" on 50050, "Java RMI" on 50050 declared, never on UDP even declared.
The fuzz target parse_java_rmi runs nightly. Its seeds are seven frames of the capture, 4, 6, 33, 53, 60, 61 and 319. It decodes the input, then each seed altered by XOR masks that the input chooses. It must neither panic nor loop. On success, the type is the first byte and every field is the one of the wire. The messages after a stream header, the arguments and the value end the input, and the hostname points into it. is_self_identifying() is true exactly for a stream header, a Call or a Return. Decoding the message after a header, Display and the accessors must not panic.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- Serialized values: the arguments and the return value stay bytes, borrowed from the segment. No object, class descriptor or exception is read. The exceptional Return of frame 69, 2 588 bytes, gives its type and its UID; the exception stays in
value. - No reassembly: a Call or a Return longer than its segment is read from its first segment. Its header is read, and
argumentsorvaluestop at the end of the segment. The next segments start in the middle of the serialized bytes, and nothing ties them to the message. The capture has none: its largest message, frame 69, fits in one segment. - One message per segment: after a Call or a Return, whatever follows goes into
argumentsorvalue. Only a SingleOp header carries a message after it, throughmessage(). - The EndpointIdentifier that the client sends after the ProtocolAck has no type byte. It starts with the high byte of the hostname length, 0 for any name under 256 bytes, and is
UnknownMessageType(0). tshark shows it as "Continuation". - MultiplexProtocol: only the header is recognized, not the multiplexed operations.
- Method names exist only for the registry and the DGC. Activator calls and application calls keep their hash.
- No session state: nothing ties a Return to its Call, or a DgcAck to its Return. The golden test does it; the crate does not.
Modbus/TCP and UMAS
Modbus/TCP wraps each Modbus PDU in a seven-byte MBAP header; UMAS, the proprietary protocol Schneider Electric uses to control its Modicon PLCs, travels inside it under the vendor function code 0x5A. Two modules, two labels: packet_parser::parse::application::protocols::modbus_tcp ("ModbusTCP") and packet_parser::parse::application::protocols::umas ("UMAS"), on TCP only. On UDP the same envelope is recognized on port 502 alone, under a third label, "ModbusUDP", since 12.0.0 (Modbus over UDP). 11.6.0 made the Modbus/TCP label depend on the port (#167).
Detection: four rules on TCP
#![allow(unused)] fn main() { // TCP 502 (IANA `mbap`): the MBAP envelope is enough, UMAS first port_rule(ApplicationProtocol::Umas, Guard::Tcp, is_modbus_tcp_port, ProbeId::Umas), port_rule(ApplicationProtocol::ModbusTcp, Guard::Tcp, is_modbus_tcp_port, ProbeId::ModbusTcp), // ... blind cascade, after SRVLOC: rule(ApplicationProtocol::Umas, Guard::Tcp, ProbeId::Umas), rule(ApplicationProtocol::ModbusTcp, Guard::Tcp, ProbeId::ModbusTcpBlind), }
UMAS comes first, on the port and off it: it is carried by a valid Modbus envelope, so the Modbus probe would accept its frames too, and the most specific protocol gets the label, as S7Comm does before COTP. Its probe, ProbeId::Umas, is the same in both rules. Since 13.1.0 it asks what Modbus/TCP asks: MBAP headers that tile the segment, each of function code 0x5A, with a session id and a UMAS function byte after it (UmasPacket::is_tcp_match, #295). Until then it read the first MBAP alone, as UmasPacket::try_from does, and ignored the rest of the segment: four bytes 5a ss ff after an MBAP header, followed by text, came out "UMAS" on any TCP port, ahead of the Modbus probe that 11.6.0 had tightened. The 181 UMAS frames of the corpus kept their label.
On TCP 502, ProbeId::ModbusTcp runs the decoder alone, ModbusTcpPacket::try_from: a well-formed envelope is enough, whatever the function code.
Elsewhere, ProbeId::ModbusTcpBlind runs ModbusTcpPacket::is_blind_tcp_match, crate-internal. The envelope was all the former blind probe checked, and it is the shape of any message that starts with two bytes and a four-byte length: off port 502, 97 segments of the corpora came out ModbusTCP, Active Directory's LDAP (30 84 00 00 .., 57 segments of The-Ultimate-PCAP.pcapng and 7 of nDPI's kerberos.pcap), DICOM, the transport protocol of Elasticsearch, a game. The probe now demands that every MBAP of the segment:
-
carry a PDU that
is_plausible_pduaccepts: a public function code of common use, and data of the size it imposes, as a request or as a response (Modbus Application Protocol v1.1b3):Function code Request Response 0x01,0x02Read Coils, Read Discrete Inputsaddress, quantity 1 to 2 000 a byte count of 1 to 250, then that many bytes 0x03,0x04Read Holding, Input Registersaddress, quantity 1 to 125 the same, with an even count 0x05Write Single Coiladdress, value 0x0000or0xFF00the echo 0x06Write Single Registeraddress, value the echo 0x0FWrite Multiple Coilsquantity 1 to 1 968, a byte count of the quantity divided by 8 rounded up, the values address, quantity 0x10Write Multiple Registersquantity 1 to 123, a byte count of twice the quantity, the values address, quantity 0x16Mask Write Registeraddress, AND mask, OR mask the echo 0x17Read/Write Multiple Registersread quantity 1 to 125, write quantity 1 to 121, the values written as a read 0x2BEncapsulated Interface TransportRead Device Identification only (MEI type 14): a read code of 1 to 4, an object id a conformity level, then objects that tile the PDU exactly 0x81–0x86,0x8F,0x90,0x96,0x97,0xABthe exception response to one of the above: one exception code, 1 to 6, 8, 10 or 11 The serial line codes (7, 8, 11, 12, 17), file record access (20, 21), FIFO queue (24), CANopen (MEI type 13, whose size the specification does not give) and the user-defined codes are refused off port; on port 502 the decoder accepts them.
-
not be one of two lookalikes whose header remains a valid Modbus PDU byte for byte:
- an Active Directory LDAPMessage,
30 84 00 00 LL LL 02 n: a SEQUENCE with a four-byte length, then the messageID INTEGER, read as unit 2 and function code n, 1 to 4. An unbindRequest(2) or an abandonRequest is a valid Read Coils there (frame 3627 ofNEWYORK.cap, OTRF datasets); - a DICOM A-ASSOCIATE-RJ,
03 00 00 00 00 04 00 r s c: the type 3 and its four-byte length, then the result read as the function code and the source as a byte count.
Off port 502, a real Modbus message loses only transaction
0x3084of unit 2 with functions 1 to 4, and, at transaction0x0300, a one-byte read response of unit 0. - an Active Directory LDAPMessage,
classify_payload, given TCP and no port (None, None), reaches the strict probe only. A Read Holding Registers request passes it, a scanner's user-defined function code does not (tested):
#![allow(unused)] fn main() { #[test] fn modbus_is_lenient_on_port_502_and_strict_elsewhere() { // A Read Holding Registers request: a common function code, and the // four bytes of data it imposes. let raw = hex::decode(MODBUS_READ_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("ModbusTCP")); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = ModbusTcpPacket::try_from(payload).unwrap(); let [mbap] = packet.mbaps.as_slice() else { panic!("one MBAP, got {}", packet.mbaps.len()); }; assert_eq!(mbap.transaction_identifier, 209); assert_eq!((mbap.protocol_identifier, mbap.length, mbap.unit_identifier), (0, 6, 1)); assert_eq!(mbap.pdu.function_code, 0x03); assert_eq!(mbap.pdu.pdu_data, [0x00, 0x01, 0x00, 0x01]); // address 1, quantity 1 let moved = with_ports(&raw, 2074, 40001); assert_eq!(label(&parse(LinkType::ETHERNET, &moved).unwrap()), Some("ModbusTCP")); // A scanner's probe with function code 0x41, of the user-defined // range: a valid envelope, which only port 502 accepts. let raw = hex::decode(MODBUS_USER_FUNCTION_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("ModbusTCP")); let moved = with_ports(&raw, 2582, 40001); assert_eq!(label(&parse(LinkType::ETHERNET, &moved).unwrap()), Some("Unknown")); } }
And an Active Directory bindResponse, frame 40035 of pcaps_exemple/The-Ultimate-PCAP.pcapng, which the decoder takes for an envelope (tested):
#![allow(unused)] fn main() { #[test] fn an_ldap_message_has_the_envelope_of_modbus_not_its_label() { let raw = hex::decode(LDAP_BIND_RESPONSE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); // 30 84 00 00 00 68: a BER SEQUENCE with a four-byte length, read as // transaction 0x3084, protocol 0 and a length that fills the segment; // then the messageID INTEGER, 02 01, read as unit 2 and function 1. let packet = ModbusTcpPacket::try_from(payload).unwrap(); let [mbap] = packet.mbaps.as_slice() else { panic!("one MBAP, got {}", packet.mbaps.len()); }; assert_eq!(mbap.transaction_identifier, 0x3084); assert_eq!(usize::from(mbap.length) + 6, payload.len()); assert_eq!((mbap.unit_identifier, mbap.pdu.function_code), (2, 1)); // On TCP 389 only the blind probe can label it, and it refuses. assert_eq!(label(&flow), Some("Unknown")); } }
On a declared port
DecodeAsProtocol::ModbusTcp gives another port the rule of port 502: (ApplicationProtocol::ModbusTcp, Guard::Tcp, ProbeId::ModbusTcp), the decoder alone. Declared ports are tried before the table, so on that port the label is "ModbusTCP" for everything the decoder accepts, UMAS included: Decode As names the protocol of the port, as it does for any protocol. There is no DecodeAsProtocol::Umas, and none is needed, since UMAS is recognized by the same probe on every port (tested, frame 6 of protocols/umas/umas.pcap):
#![allow(unused)] fn main() { #[test] fn umas_keeps_its_label_off_port_a_declared_modbus_port_does_not() { let raw = hex::decode(UMAS_REPLY_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("UMAS")); // 502 -> 7718: UMAS comes before ModbusTCP let umas = UmasPacket::try_from(flow.transport.as_ref().unwrap().payload.unwrap()).unwrap(); assert_eq!(umas.mbap.pdu.function_code, 0x5A); assert_eq!(umas.session_id, 0x00); assert_eq!(umas.function, UmasFunction::Reply); // 0xFE assert!(umas.data.windows(14).any(|bytes| bytes == b"140 CPU 311 10")); // the PLC's model // Off port 502 the UMAS probe is the same: still UMAS. let moved = with_ports(&raw, 40001, 7718); assert_eq!(label(&parse(LinkType::ETHERNET, &moved).unwrap()), Some("UMAS")); // A port declared as Modbus/TCP is tried before the table, with the // tolerant decoder: the label is the declared protocol. let config = ParseConfig::new().decode_as(40001, DecodeAsProtocol::ModbusTcp); let flow = parse_with(LinkType::ETHERNET, &moved, &config).unwrap(); assert_eq!(label(&flow), Some("ModbusTCP")); } }
Modbus over UDP
Modbus over UDP is not in the Modbus Messaging on TCP/IP specification, but devices speak it, with the same MBAP envelope in each datagram, and Wireshark has a dissector for it (mbudp, UDP 502). Until 12.0.0 the crate labelled those datagrams "Unknown": every Modbus rule had a TCP guard (#257). 12.0.0 adds one port rule:
#![allow(unused)] fn main() { // right after the two rules of TCP 502 port_rule(ApplicationProtocol::ModbusUdp, Guard::Udp, is_modbus_udp_port, ProbeId::ModbusTcp), }
The probe is the one of TCP 502, the decoder alone, and the decoder is the same, ModbusTcpPacket::try_from. The label is its own, "ModbusUDP" (ApplicationProtocol::ModbusUdp): "ModbusTCP" on a datagram would name the wrong transport. Another UDP port is declared with DecodeAsProtocol::ModbusUdp.
There is no blind rule on UDP. Measured on the crate's corpus (387 123 frames, 111 416 UDP flows), the decoder accepts the 38 Modbus datagrams of UDP 502, and 106 more off that port, all of them CLDAP on UDP 389: an LDAPMessage whose BER length is written on four bytes has the shape of an MBAP envelope, as it does on TCP, above. The strict probe of the TCP cascade accepts none of the 106, but one corpus is not enough to trust it on every UDP port. UMAS has no rule on UDP either, for want of a capture: a UMAS message on UDP 502 would be "ModbusUDP".
The 38 datagrams are frames 50281 to 50318 of pcaps_exemple/The-Ultimate-PCAP.pcapng, 19 requests and 19 responses, checked one by one against tshark (tests/modbus_golden.rs). The first is a Read Coils request (tested):
#![allow(unused)] fn main() { #[test] fn modbus_on_udp_502_has_its_own_label() { let raw = hex::decode(MODBUS_UDP_READ_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let application = flow.application.as_ref().unwrap(); assert_eq!(application.protocol, ApplicationProtocol::ModbusUdp); assert_eq!(application.protocol.label(), "ModbusUDP"); // The decoder is the one of Modbus/TCP: the same MBAP envelope. let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = ModbusTcpPacket::try_from(payload).unwrap(); let [mbap] = packet.mbaps.as_slice() else { panic!("one MBAP, got {}", packet.mbaps.len()); }; assert_eq!(mbap.transaction_identifier, 1); assert_eq!((mbap.protocol_identifier, mbap.length, mbap.unit_identifier), (0, 6, 1)); assert_eq!(mbap.pdu.function_code, 0x01); assert_eq!(mbap.pdu.pdu_data, [0x05, 0x00, 0x00, 0x03]); // address 1280, quantity 3 // Off UDP 502 nothing probes for Modbus, unless the port is declared. let moved = with_ports(&raw, 38956, 40001); assert_eq!(label(&parse(LinkType::ETHERNET, &moved).unwrap()), Some("Unknown")); let declared = ParseConfig::new().decode_as(40001, DecodeAsProtocol::ModbusUdp); let flow = parse_with(LinkType::ETHERNET, &moved, &declared).unwrap(); assert_eq!(label(&flow), Some("ModbusUDP")); // The same payload without its frame: `classify_payload` gives the // label of `parse`. With no port, UDP has no Modbus rule to try; TCP // has the strict blind probe. let udp = TransportProtocol::Udp; let label_of = |protocol, source, destination| { classify_payload(protocol, source, destination, payload) .map(|application| application.protocol) }; assert_eq!(label_of(udp, Some(38956), Some(502)), Some(ApplicationProtocol::ModbusUdp)); assert_eq!(label_of(udp, None, None), Some(ApplicationProtocol::Unknown)); assert_eq!( label_of(TransportProtocol::Tcp, None, None), Some(ApplicationProtocol::ModbusTcp) ); } }
The envelope and the UMAS header
#![allow(unused)] fn main() { pub struct ModbusTcpPacket<'a> { pub mbaps: Vec<MBAP<'a>>, // several MBAPs in one segment } pub struct MBAP<'a> { pub transaction_identifier: u16, pub protocol_identifier: u16, pub length: u16, pub unit_identifier: u8, pub pdu: Modbus<'a>, } pub struct Modbus<'a> { pub function_code: u8, pub pdu_data: &'a [u8], } }
All three are #[non_exhaustive]. The MBAPs must tile the segment, each one starting where the previous one ends, 6 + length bytes later; all errors are ModbusTcpError, in packet_parser::errors::application::modbus_tcp:
| Bytes | Field | Check | Error |
|---|---|---|---|
| at least 7 bytes left for each MBAP | BufferTooSmall { needed, actual } | ||
| 0–1 | transaction_identifier | ||
| 2–3 | protocol_identifier | 0 | InvalidProtocolIdentifier { got } |
| 4–5 | length | 1 or more, and 6 + length bytes present | InvalidLengthField { got }, LengthMismatch { expected, actual } |
| 6 | unit_identifier | ||
| 7 | pdu.function_code | present | PduTooSmall { needed, actual } |
8 to 5 + length | pdu.pdu_data |
The decoder does not interpret the function code: is_plausible_pdu is a detection check, not a decode, and the data stay raw.
#![allow(unused)] fn main() { pub struct UmasPacket<'a> { pub mbap: MBAP<'a>, // the carrying envelope, function code 0x5A pub session_id: u8, // given by the PLC pub function: UmasFunction, // a request's code or a reply's status pub data: &'a [u8], // not decoded } }
UmasPacket::try_from decodes the first MBAP of the segment and needs function code 0x5A (UmasError::NotUmas { got }) and two bytes after it, the session id and the function (UmasError::PduTooSmall { needed, actual }); an invalid envelope is UmasError::InvalidEnvelope, which wraps the ModbusTcpError. UMAS has no public specification and the names of its request codes come from reverse engineering, which no capture can confirm: UmasFunction names only what a frame of the corpus attests, Reply (0xFE, the constant UMAS_REPLY, carried by the 90 replies of umas.pcap), and leaves every other value as Other(u8).
Oracle: 601 segments
tests/modbus_golden.rs compares every MBAP header with tshark 4.6.6 (tools/modbus_oracle.sh, frozen in tests/data/modbus_tshark_oracle.tsv): transaction, length, unit, function code and exception code. The segments are those of protocols/modbus/, protocols/umas/ and, read in place, The-Ultimate-PCAP.pcapng.
| What the test counts | Segments |
|---|---|
| Modbus/TCP segments compared with tshark | 601 |
of them, labelled "ModbusTCP" | 420 |
of them, labelled "UMAS" | 181 |
| missed by the crate | 0 |
| still recognized once moved off port 502 | 358 |
| recognized on port 502 only | 243 |
The crate labels no other segment of these captures Modbus. The Ultimate PCAP has 400 TCP 389 segments with a payload, LDAP and the TLS that follows StartTLS: 57 of them have the MBAP shape, and none is labelled. The 243 segments that need port 502 are the probes of a scanner that tries the 128 request codes 0x00 to 0x7F, and their exception responses (MODBUS-TestDataPart2.pcap).
tests/umas_golden.rs checks the 180 UMAS frames of umas.pcap: two sessions and fourteen values of the function byte. The 38 datagrams of Modbus over UDP have their own comparison in the same test as the TCP segments, against tests/data/modbus_udp_tshark_oracle.tsv (tools/modbus_udp_oracle.sh). The golden histogram counts 382 ModbusTCP, 181 UMAS and 38 ModbusUDP labels.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- The PDU. The decoder does not interpret the function code, and the data stay raw: no register, no coil, no exception name.
is_plausible_pduis a detection check, internal to the crate. - UMAS beyond its header. The session id and the function byte are read;
datais not decoded, andUmasFunctionnames onlyReply. - UMAS over UDP. No rule looks for it: on UDP 502 it is
"ModbusUDP". - Modbus over UDP off port 502. There is no blind rule; another port must be declared.
- Serial Modbus. RTU and ASCII framing, and Modbus RTU carried over TCP without an MBAP header, have no decoder.
- Pairing. Nothing matches a response to its request by transaction identifier.
NMF
NMF, the .NET Message Framing protocol ([MC-NMF]), is what a WCF service speaks on a net.tcp:// binding: it cuts a TCP stream into SOAP messages. Each end opens with a short preamble, then sends its messages as envelopes. The decoder was added in 13.3.0 (#351, #352, PR #359). The module is packet_parser::parse::application::protocols::nmf, the errors are NmfError, in packet_parser::errors::application::nmf, and the label is "NMF".
#![allow(unused)] fn main() { pub struct NmfSegment<'a> { /* the TCP segment, validated */ } pub enum NmfRecord<'a> { Version { major: u8, minor: u8 }, // 0x00: always 1.0 Mode(NmfMode), // 0x01 Via(&'a str), // 0x02: the URI the messages are bound to KnownEncoding(u8), // 0x03: a well-known encoding, by number ExtensibleEncoding(&'a str), // 0x04: an encoding named by its MIME type UnsizedEnvelope { chunks: &'a [u8] },// 0x05: a message sent as chunks SizedEnvelope { declared_length: u32, payload: &'a [u8] }, // 0x06 End, // 0x07: end of the session Fault(&'a str), // 0x08: a fault, named by a URI UpgradeRequest(&'a str), // 0x09: TLS or Negotiate, by name UpgradeResponse, // 0x0A PreambleAck, // 0x0B PreambleEnd, // 0x0C } pub enum NmfMode { SingletonUnsized, Duplex, Simplex, SingletonSized } // 1 to 4 }
A segment is a run of records, and a record is a type byte followed by nothing, by one byte, or by a size and that many bytes. NmfSegment::try_from validates the whole segment once; records() then gives the records in wire order without allocating, and as_bytes() the segment. The types are #[non_exhaustive], and the strings and payloads borrow from the segment. record_type() gives the type byte of a record.
A size ([MC-NMF] §2.2.2) is written on one to five bytes, seven bits in each, the low bits first; the high bit of a byte says that another follows. 41 is 29; 1 106 is D2 08.
The preamble a client sends first (tested):
#![allow(unused)] fn main() { #[test] fn a_preamble_and_its_records() { let raw = hex::decode(PREAMBLE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("NMF")); let segment = NmfSegment::try_from(payload(&flow)).unwrap(); let records: Vec<_> = segment.records().collect(); let [version, mode, via, encoding, end] = records[..] else { panic!("expected five records, got {records:?}"); }; assert_eq!(version, NmfRecord::Version { major: 1, minor: 0 }); assert_eq!(mode, NmfRecord::Mode(NmfMode::Duplex)); // The URI the session is bound to: 41 bytes, censored to x's. let NmfRecord::Via(uri) = via else { panic!("expected a Via, got {via:?}") }; assert!(uri.starts_with("net.tcp://host/")); assert_eq!(uri.len(), 41); // 8: binary XML with a session dictionary, the default of net.tcp. assert_eq!(encoding, NmfRecord::KnownEncoding(8)); assert_eq!(end, NmfRecord::PreambleEnd); // The record type is the first byte of each record. let types: Vec<u8> = records.iter().map(NmfRecord::record_type).collect(); assert_eq!(types, [0x00, 0x01, 0x02, 0x03, 0x0C]); } }
The message itself is not decoded. The payload of an envelope is a SOAP message, most often in the binary XML of [MC-NBFSE], and it is returned as bytes.
Detection: any TCP port
| Where | Rule | Probe | Accepts |
|---|---|---|---|
| any TCP port | blind rule 76 | ProbeId::NmfBlind | a segment NmfSegment::try_from accepts and that opens with a preamble or with a sized envelope in binary XML |
a TCP port declared with ParseConfig::decode_as(port, DecodeAsProtocol::Nmf) | tried before the table | ProbeId::Nmf | any segment NmfSegment::try_from accepts |
NMF has no registered port: 808 is the default of the Net.TCP port sharing service, and a service listens where its configuration says. Rule 76 sits near the end of the blind cascade of the table, before DCE/RPC and MQTT. A decoder alone would be far too weak a probe: a record may be one byte long, and 0x07 proves nothing. The blind rule therefore accepts two openings only, each with a signature of several bytes:
- a preamble: a Version record, 1.0, a Mode record, then a Via record whose text holds
://. That is00 01 00 01, a mode from 1 to 4,02, a size and a URI in UTF-8; - a sized envelope in binary XML: the payload starts with the string table of [MC-NBFSE], a size followed by length-prefixed UTF-8 strings that fill it exactly, then
56 02 0B 01 73. Those five bytes are the elements:Envelopeof the static dictionary of [MC-NBFS] and the declaration of its prefix: the first bytes of every SOAP message in that encoding.
Everything else needs a declared port: the acknowledgement of the preamble and the end of the session, one byte each, an envelope in another encoding, a fault. DecodeAsProtocol::Nmf resolves to the label NMF, the guard Tcp and the probe Nmf, the decoder alone (tested):
#![allow(unused)] fn main() { #[test] fn a_one_byte_record_needs_a_declared_port() { let raw = hex::decode(PREAMBLE_ACK_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); // The padding after the segment is not part of the payload. assert_eq!(payload(&flow), [0x0B]); // The decoder reads it, but one byte is no signature: the blind // rule leaves it alone. let segment = NmfSegment::try_from(payload(&flow)).unwrap(); assert_eq!(segment.records().next(), Some(NmfRecord::PreambleAck)); assert_eq!(label(&flow), Some("Unknown")); // On a port the caller declares, every segment that splits into // records is NMF. let config = ParseConfig::new().decode_as(50001, DecodeAsProtocol::Nmf); let flow = parse_with(LinkType::ETHERNET, &raw, &config).unwrap(); assert_eq!(label(&flow), Some("NMF")); } }
Validations
| Part | Check | Error |
|---|---|---|
| Segment | not empty | NmfError::Empty |
| Record type | 0x00 to 0x0C | UnknownRecordType |
| Version | three bytes, and 1.0 | TruncatedRecord, UnsupportedVersion { major, minor } |
| Mode | two bytes, and 1 to 4 | TruncatedRecord, InvalidMode |
| Known encoding | two bytes | TruncatedRecord |
| Size | at most five bytes, and a value that fits in 32 bits | MalformedSize |
| Via, extensible encoding, fault, upgrade request | the string is whole in the segment | TruncatedRecord { record_type, expected, actual } |
| The same four | valid UTF-8 | InvalidString { record_type } |
The records are read one after the other until the end of the segment, and the first failure is the error. Two records are allowed to run past it, because a message is often longer than a segment:
- a sized envelope keeps the size it announces in
declared_lengthand, inpayload, the bytes the segment holds.is_truncated()says that the message goes on in the next segment; - an unsized envelope takes everything up to the end of the segment as its chunks, without splitting them.
A record after a truncated envelope cannot exist: the envelope ends the segment. What the decoder refuses, on the bytes of the preamble (tested):
#![allow(unused)] fn main() { #[test] fn what_nmf_refuses() { let raw = hex::decode(PREAMBLE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let preamble = payload(&flow); // A Version record is three bytes. assert_eq!( NmfSegment::try_from(&preamble[..2]).unwrap_err(), NmfError::TruncatedRecord { record_type: 0x00, expected: 3, actual: 2 } ); // A Via cut inside its URI: 43 bytes announced, 20 in the segment. assert_eq!( NmfSegment::try_from(&preamble[5..25]).unwrap_err(), NmfError::TruncatedRecord { record_type: 0x02, expected: 43, actual: 20 } ); // The same bytes read from the URI on: `n` is no record type. assert_eq!( NmfSegment::try_from(&preamble[7..]).unwrap_err(), NmfError::UnknownRecordType(b'n') ); assert_eq!(NmfSegment::try_from(&preamble[..0]).unwrap_err(), NmfError::Empty); } }
What is not NMF
Each row was checked against the crate, on a TCP port without a rule of its own, then on the same port declared Nmf:
| Payload | Blind | Declared | Why |
|---|---|---|---|
| the preamble of the example | "NMF" | "NMF" | |
| the preamble without its last two records | "NMF" | "NMF" | Version, Mode and Via are the signature |
| its Version and Mode records alone | "Unknown" | "NMF" | five bytes, no Via |
the acknowledgement, 0B | "Unknown" | "NMF" | one byte is no signature |
| the start of a sized envelope in binary XML | "NMF" | "NMF" | truncated, and named by its opening |
a sized envelope of three bytes, abc | "Unknown" | "NMF" | its payload does not open as [MC-NBFSE] |
| forty null bytes | "Unknown" | "Unknown" | UnsupportedVersion: a Version record of 0.0 |
| the preamble, on UDP | "Unknown" | "Unknown" | the guard is TCP |
| a DCE/RPC Bind | "DCE/RPC" | "NMF" | its first byte, 05, opens an unsized envelope |
The last row is a warning about declared ports. An unsized envelope has no size to check, so on a port declared Nmf any segment that starts with 05 is NMF. Declare the port of a service you know to be WCF, not a range.
Oracle: 23 segments
No public NMF capture was found: the Wireshark tracker has fuzz files only. pcaps_exemple/protocols/nmf/terrain_nmf_censure.pcap is 32 frames of a field capture of the maintainer, censored by tools/censor_capture.py before they were published. Addresses, ports, the URI of the Via record, the strings of the string tables and the bodies of the messages were rewritten; record types, sizes, the mode, the encoding and the segmentation are the original ones. Its SOURCE.md lists each rewritten field, and tshark reads the same records before and after.
The golden test tests/nmf_golden.rs compares the crate with tshark 4.6.9, which is told the two service ports. tools/nmf_oracle.sh freezes, in tests/data/nmf_tshark_oracle.tsv, one line per segment with a payload: its record types, the size of its envelope, the mode, the encoding and the length of the Via.
| Segments | What | Without Decode As | Ports declared |
|---|---|---|---|
| 1 | the preamble | "NMF" | "NMF" |
| 5 | sized envelopes: four whole messages, and the first segment of a message of 50 253 bytes | "NMF" | "NMF" |
| 2 | the acknowledgement and the end of the session, one byte each | "Unknown" | "NMF" |
| 15 | continuation segments, in the middle of a message | "Unknown" | "Unknown" |
The test checks that the eight segments of the first three rows split into the records tshark reads, field by field, and that the long envelope is cut by its segment with is_truncated(). tshark does not reassemble here either, and reads the fifteen continuation segments as records; the crate does not. In the golden histogram "NMF" went from 0 to 6.
What is left out
The limits every protocol shares are on the Limits page. The ones below are this protocol's own.
- Continuation segments. A message of 50 KiB is one labelled segment followed by some thirty-four that are
"Unknown". On a real WCF flow most segments are in that case: the label of a flow is the label of its first segments (Limits). - Text SOAP and binary XML without a session dictionary. No real frame of the corpus carries them, so the blind rule does not know them: they are named on a declared port only.
- Unsized envelopes are not split into chunks, and their end is not looked for.
- After an upgrade, the stream is TLS or Negotiate: it is no longer readable NMF, and TLS is labelled TLS.
- The message. Neither the string table nor the binary XML is decoded.
NTP
Network Time Protocol, RFC 5905, on UDP only. The module is packet_parser::parse::application::protocols::ntp; NtpPacket::try_from decodes the 48-byte header, and NtpPacketParseError, in packet_parser::errors::application::ntp, says why it refused. 11.6.0 reworked both sides of the detection with real captures: the decoder stopped refusing real traffic (#161, #162, #165), and the blind probe stopped accepting traffic that was not NTP (#164).
Detection: lenient on port 123, strict elsewhere
#![allow(unused)] fn main() { port_rule(ApplicationProtocol::Ntp, Guard::Udp, is_ntp_udp_port, ProbeId::Ntp), // 123, the last port rule // --- blind cascade --- rule(ApplicationProtocol::Ntp, Guard::Udp, ProbeId::NtpBlind), // the first blind rule }
On UDP 123, either port (a server's source, a client's destination, both in symmetric mode), ProbeId::Ntp runs the decoder alone. The rule is the last of the port rules. Until 11.6.0 the blind rule stood at that place, with the same decoder, so the move changed nothing on port 123. Being last, the rule also lets every other port rule speak first: a DNS query sent from port 123 to port 53 keeps the label DNS even when its bytes read as an NTP header. The unit tests of the dispatch pin that case down.
On any other UDP port, ProbeId::NtpBlind runs NtpPacket::is_blind_udp_match, crate-internal, on the whole datagram. The decoder must accept the datagram, and the header alone is not enough: until 11.6.0 the blind probe was the decoder, and about one random datagram in 250 passed for NTP; on the 654 test captures of nDPI, 43 of the 59 NTP labels were wrong (QUIC, CryNet, Gnutella, KCP, PFCP, NetBIOS datagrams, obfuscated OpenVPN...). The probe now also demands:
| What | Required off port 123 | Why |
|---|---|---|
| poll | -7 to 24 | chrony's range; ntpd uses 3 to 17, an SNTP client 0; the false positives of nDPI carried 46 to 118 |
| precision | -32 to 0, or 32 | 2⁻³² s is the resolution of a timestamp; chrony puts 32 in its client requests |
| root delay | under 16 s (MAXDISP) | the largest real one of the corpora is 1 s; a QUIC v1 header reads as 256 s or more |
| bytes after the header | none; in NTPv4, extension fields (16 bytes or more, a multiple of 4), then an optional MAC: 4 zero bytes (crypto-NAK), 20 bytes (MD5, AES-CMAC) or 24 (SHA-1); or a MAC alone of 36, 52 or 68 bytes (SHA-256, SHA-384, SHA-512); before NTPv4, a crypto-NAK or a MAC of 12 to 72 bytes, the longest being the Extended Authenticator of MS-SNTP | they must end exactly with the datagram |
| Receive and Transmit | Receive not after Transmit, a null timestamp not compared | both are on the sender's clock |
| reference id at stratum 0 | null, an ASCII code, or 127.0.0.1 | the decoder accepts any four bytes there |
The root dispersion is not bounded: the stratum 1 ntpd of the second example below announces 107.8 s. Measured by #164 on the nDPI captures, the crate now labels exactly the 16 NTP datagrams of modes 1 to 5 that tshark sees there, and none of the 202 558 other UDP datagrams of the 3 110 captures examined. Application::try_from, which has no port, uses the strict probe too, and there is no DecodeAsProtocol::Ntp.
The examples of this page, like those of Modbus and PostgreSQL, move a real frame off its port with a small helper:
#![allow(unused)] fn main() { /// The same frame with other transport ports: Ethernet, IPv4 (header /// length in the low nibble of byte 14), then TCP or UDP, whose first /// four bytes are the two ports. `parse` verifies no checksum, so nothing /// else changes. fn with_ports(raw: &[u8], source: u16, destination: u16) -> Vec<u8> { let ports = 14 + usize::from(raw[14] & 0x0f) * 4; let mut moved = raw.to_vec(); moved[ports..ports + 2].copy_from_slice(&source.to_be_bytes()); moved[ports + 2..ports + 4].copy_from_slice(&destination.to_be_bytes()); moved } }
Frame 3 of pcaps_exemple/protocols/ntp/tcpdump_ntp.pcap, a chrony request, is NTP on its port and nowhere else (tested):
#![allow(unused)] fn main() { #[test] fn ntp_is_lenient_on_port_123_and_strict_elsewhere() { let raw = hex::decode(NTP_CHRONY_REQUEST_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("NTP")); // 42818 -> 123: the decoder alone let payload = flow.transport.as_ref().unwrap().payload.unwrap(); assert_eq!(payload.len(), 48 + 24); // the header, then a key id and a SHA-1 digest let request = NtpPacket::try_from(payload).unwrap(); assert_eq!(request.flags, (0, 4, 3)); // leap indicator 0, version 4, mode 3: client assert_eq!(request.precision, 32); // what chrony puts in its client requests // chrony fills Receive and Transmit with random values: here Receive // falls in 2093 and Transmit in 1992. assert!(request.receive_timestamp.to_string().starts_with("2093-03-22")); assert!(request.transmit_timestamp.to_string().starts_with("1992-10-31")); // The same bytes off port 123: the blind probe also wants Receive // not after Transmit, and refuses them. let moved = with_ports(&raw, 42818, 40001); let flow = parse(LinkType::ETHERNET, &moved).unwrap(); assert_eq!(label(&flow), Some("Unknown")); } }
The header
#![allow(unused)] fn main() { pub struct NtpPacket { pub flags: (u8, u8, u8), // leap indicator, version, mode pub stratum: u8, pub poll: u8, // the raw byte: poll_exponent() gives it signed pub precision: i8, pub root_delay: u32, pub root_dispersion: u32, pub reference_id: Refid, pub reference_timestamp: NtpTimestamp, pub originate_timestamp: NtpTimestamp, pub receive_timestamp: NtpTimestamp, pub transmit_timestamp: NtpTimestamp, } pub struct NtpTimestamp { pub seconds: u32, // since the start of the era pub fraction: u32, // in units of 2^-32 s } pub enum Refid { Ipv4(Ipv4Addr), // stratum 2 to 15 KissCode([u8; 4]), // stratum 0 ClockSource([u8; 4]), // stratum 1 } }
Both are #[non_exhaustive]. The decoder reads the header in wire order; the bytes after it (extension fields, MAC) are not decoded, and only the blind probe looks at them.
| Bytes | Field | Check | Error |
|---|---|---|---|
| at least 48 bytes | InvalidPacketLength | ||
| 0 | flags: LI (bits 7–6), VN (5–3), mode (2–0) | version 1 to 4, mode 1 to 5 | InvalidVersion { version }, InvalidMode { mode } |
| 1 | stratum | 0 to 15 | InvalidStratum |
| 2 | poll | signed, -7 or more | InvalidPoll |
| 3 | precision | ||
| 4–7 | root_delay | ||
| 8–11 | root_dispersion | ||
| 12–15 | reference_id | at stratum 1, a printable ASCII code | InvalidReferenceIdForStratum1 |
| 16–23 | reference_timestamp | ||
| 24–31 | originate_timestamp | ||
| 32–39 | receive_timestamp | ||
| 40–47 | transmit_timestamp |
Mode 6 (control messages, ntpq) and mode 7 are refused: NtpPacket does not model their format. InconsistentTimestamps no longer comes out of try_from, which compares no timestamps (below).
The reference id depends on the stratum (RFC 5905 §7.3), and 11.6.0 widened the three cases:
- stratum 1: a clock source, printable ASCII, left-justified and zero-padded. The list is kept by IANA and is longer than the RFC's excerpt (GOES, GPS, PPS...): any non-empty printable code is accepted,
SHM, ntpd's shared memory driver, included (#162); - stratum 0: a kiss code in a server's Kiss-o'-Death, but whatever an unsynchronized client leaves in its request (
127.0.0.1,USER): any four bytes, kept asKissCode(#165); - stratum 2 to 15: the IPv4 address of the upstream server or, for an IPv6 upstream, the first four bytes of the MD5 hash of its address, which can read as any address, multicast included: any four bytes, kept as
Ipv4(#165).
Refid::code() gives the code of a kiss code or clock source without its padding, and Display prints the code, the address, NULL for an empty kiss code, or the bytes. The poll is a signed power of two (RFC 5905 §7.3), down to -7 for chrony since its version 4.3; the decoder used to refuse it as soon as it was negative. poll keeps the byte as received (-7 is 249) and NtpPacket::poll_exponent() returns it signed (#165). Before #165, 27 NTP packets of The-Ultimate-PCAP.pcapng came out "Unknown".
Timestamps: an era and two clocks
A timestamp is 32 bits of seconds since the start of an era and 32 bits of fraction. Since 13.0.0 the crate keeps them as they are on the wire, in NtpTimestamp; until 12.x it turned them into a DateTime<Utc> of chrono, which is no longer maintained (RUSTSEC-2026-0543) and is no longer a dependency #315. The dates did not change: they were checked against tshark on every NTP datagram of the corpus. The type reads them:
| Method | Gives |
|---|---|
unix_seconds() | whole seconds since 1970, negative before; 0 for a null timestamp |
subsec_nanos() | the fraction, in nanoseconds, rounded down |
is_null() | whether all 64 bits are zero: "unknown" |
to_system_time() | a SystemTime, None only where the platform cannot hold the date |
Display | RFC 3339 in UTC, to the nanosecond: 2008-07-31T11:45:31.067669303Z |
Ord | the order in time, eras included |
NtpPacketParseError::TimestampConversionError is gone: every timestamp has a date. The rules:
- the era is given by the most significant bit of the seconds (RFC 4330 §3): set, era 0, from 1968 to 2036; clear, era 1, from 2036 to 2104, as tshark reads it. Until 11.6.0 every timestamp counted from 1900, and a Java client of the corpus that sent 37 seconds came out at
1900-01-01T00:00:37Z, where tshark reads2036-02-07T06:28:53Z(#162); - an all-zero timestamp means "unknown" (RFC 5905 §6) and comes out as the Unix epoch,
1970-01-01T00:00:00.000000000Z; - the fraction becomes nanoseconds, rounded down.
Originate (T1) is the client's timestamp, copied as is into the reply; Reference, Receive (T2) and Transmit (T3) are the server's. Until 11.6.0 the decoder demanded reference <= originate <= receive <= transmit: as soon as the client's clock was a few milliseconds ahead, which is what NTP is there to correct, or a first request left originate null, the server's reply was InconsistentTimestamps, hence "Unknown", and so were 20 of the 26 real replies of the IEC 61850 substation of protocols/goose/iti_Sample_File_MMS_and_GOOSE.pcap (#161). The decoder now compares no timestamp: Receive and Transmit do share a clock, but in interleaved mode (chrony xleave) a reply carries the Transmit of the previous one (#165). Only the blind probe checks that Receive does not follow Transmit.
The exchange of the Java client of protocols/iec104/iti_JavaRMI_and_IEC_Misc.pcap, frames 1 and 2, shows the era, the null timestamp and the two clocks (tested):
#![allow(unused)] fn main() { #[test] fn ntp_timestamps_have_an_era_and_two_clocks() { // The Java client's request. Its one timestamp, Transmit, counts 37 // seconds with the high bit clear: era 1, which starts in 2036. let raw = hex::decode(NTP_JAVA_REQUEST_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("NTP")); let request = NtpPacket::try_from(flow.transport.as_ref().unwrap().payload.unwrap()).unwrap(); assert_eq!(request.stratum, 0); assert_eq!(request.transmit_timestamp.to_string(), "2036-02-07T06:28:53.000000000Z"); // An all-zero timestamp is "unknown", and comes out as the Unix epoch. assert!(request.receive_timestamp.is_null()); assert_eq!(request.receive_timestamp.to_string(), "1970-01-01T00:00:00.000000000Z"); // The server's reply. Its clock source is SHM, ntpd's shared memory // driver, which the RFC's list of codes does not name. let raw = hex::decode(NTP_SHM_REPLY_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("NTP")); let reply = NtpPacket::try_from(flow.transport.as_ref().unwrap().payload.unwrap()).unwrap(); assert_eq!(reply.flags, (0, 4, 4)); // mode 4: server assert_eq!(reply.stratum, 1); assert_eq!(reply.precision, -19); assert_eq!(reply.root_dispersion >> 16, 107); // 16.16 seconds: 107.8 s, not bounded assert_eq!(reply.reference_id, Refid::ClockSource(*b"SHM\0")); assert_eq!(reply.reference_id.to_string(), "SHM"); // Originate is the client's Transmit, copied back: 2036 on the // client's clock, after the 2008 of the server's Receive. Only // Receive and Transmit share a clock. assert_eq!(reply.originate_timestamp, request.transmit_timestamp); assert!(reply.originate_timestamp > reply.receive_timestamp); assert_eq!(reply.receive_timestamp.to_string(), "2008-07-31T11:45:31.067669303Z"); assert!(reply.receive_timestamp <= reply.transmit_timestamp); // Both datagrams are NTP for the blind probe too, off port 123. for (hex_frame, source, destination) in [(NTP_JAVA_REQUEST_HEX, 1027, 40001), (NTP_SHM_REPLY_HEX, 40001, 1027)] { let moved = with_ports(&hex::decode(hex_frame).unwrap(), source, destination); assert_eq!(label(&parse(LinkType::ETHERNET, &moved).unwrap()), Some("NTP")); } } }
Oracle: 1 308 datagrams
tests/ntp_golden.rs compares the crate with tshark 4.6.6 (tools/ntp_oracle.sh, frozen in tests/data/ntp_tshark_oracle.tsv) on 1 308 datagrams, field by field: ports, LI, version, mode, stratum, poll, precision, root delay and dispersion, reference id, and the four timestamps to the nanosecond.
The datagrams come from pcaps_exemple/protocols/ntp/, the substation of goose/iti_Sample_File_MMS_and_GOOSE.pcap, the Java exchange and, read in place, The-Ultimate-PCAP.pcapng and 4SICS-GeekLounge-151020.pcap. They cover NTS, authenticated MS-SNTP, SHA-256 and SHA-512 MACs, chrony requests with random timestamps, symmetric mode and IPv6 upstreams.
| What the test counts | Datagrams |
|---|---|
| compared with tshark | 1 308 |
| control messages of mode 6, a named gap | 104 |
| ICMP errors quoting an NTP datagram, where the crate labels the ICMP frame, a named gap | 36 |
| datagrams of six nDPI captures that the former blind probe took for NTP, named one by one | 31 |
| datagrams that only the lenient decoder of #165 accepts, named too | 8 |
| of the 1 308, recognized by the blind probe once moved off port 123 | 1 307 |
The two gaps are named, not masked, and no other frame of pcaps_exemple/ comes out NTP. The 39 named datagrams are KCP, QUIC and CryNet datagrams, and ASTERIX CAT 021 datagrams of wireshark_9953_cat021023.pcap, 1 555 of which have the shape of an NTP header. The one datagram the blind probe refuses is the chrony request of the example above. The golden histogram counts 77 NTP labels.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- Modes 6 and 7. Control messages (
ntpq) and the private mode are refused:NtpPacketdoes not model their format. The 104 mode 6 messages of the corpus come out"Unknown". - What follows the header. Extension fields, NTS fields and the MAC are not decoded; only the blind probe looks at them.
- TCP. Both rules have a UDP guard.
- The exchange. The decoder compares no timestamp with another, and nothing pairs a reply with its request: the offset and the delay of RFC 5905 §8 are the consumer's to compute.
- An NTP datagram quoted by an ICMP error. The frame is labelled as ICMP, and the quoted datagram is not probed.
PostgreSQL
The frontend/backend protocol of PostgreSQL, on TCP only. The module is packet_parser::parse::application::protocols::postgresql: PostgreSqlPacket::try_from splits a segment into PostgreSqlMessages and decodes the bodies of the main ones; its errors are PostgreSqlError, in packet_parser::errors::application::postgresql. The largest single-file decoder of the crate had no real frame to exercise it until #98 brought fourteen captures of Zeek's test corpus, and they rewrote its detection.
Two message formats, two new types
A typed message is one type byte, a u32 length that counts itself but not the type byte, and a body; the messages of a segment must tile it exactly. The first messages of a connection have no type byte: a u32 length equal to the whole payload, then a code, protocol 3.0 or 3.2 for a StartupMessage, or the code of SSLRequest, CancelRequest or GSSENCRequest. try_from tries the typed form first, then the untyped one, and reports the typed error if both fail.
#![allow(unused)] fn main() { pub struct PostgreSqlPacket<'a> { pub messages: Vec<PostgreSqlMessage<'a>>, } pub struct PostgreSqlMessage<'a> { pub message_type: PostgreSqlMessageType, pub length: u32, // typed messages: excludes the type byte pub payload: &'a [u8], // the body pub body: PostgreSqlMessageBody<'a>, } }
11.6.0 added two variants at the end of PostgreSqlMessageType, and one to PostgreSqlMessageBody:
PasswordOrSaslResponse, the type bytep, which PasswordMessage, SASLInitialResponse, SASLResponse and GSSResponse share and only the state of the authentication tells apart; the body staysRaw. The decoder used to reject the byte, so every password or SCRAM authentication came outInvalidMessageType.SslResponse: the server's one-byte answer toSSLRequest,S(TLS accepted) orN, with the bodyPostgreSqlMessageBody::SslResponse { accepted }. It has neither header nor length, so it is decoded only alone in its segment:SandNare answers,SNis an error.
Detection: compatible shape on port 5432, strong proof elsewhere
#![allow(unused)] fn main() { port_rule(ApplicationProtocol::PostgreSql, Guard::Tcp, is_postgresql_tcp_port, ProbeId::PostgresqlPort), // 5432 // ... blind cascade, after EtherNet/IP: rule(ApplicationProtocol::PostgreSql, Guard::Tcp, ProbeId::Postgresql), }
Both probes are crate-internal, both start from a successful decode, and both demand that every message have a compatible shape, a body consistent with its type: plain text in a Query or a Parse, I, T or E in a ReadyForQuery, two C-strings in a ParameterStatus whatever its name, a known authentication code of the right size, a C-string or a SASL form in a p message...
On TCP 5432 (IANA postgresql), or on a port declared with DecodeAsProtocol::PostgreSql, is_plausible_postgresql_payload stops there: a decode of compatible shape is enough. That is what recognizes the messages that carry no proof of their own: a Terminate, a ReadyForQuery or a password alone in their segment, and the S or N answer to SSLRequest. Measured on the Zeek corpus, it labels nothing in the HTTP and MySQL sessions replayed on 5432.
Elsewhere, is_likely_postgresql_payload first discards at constant cost a payload whose first bytes cannot start a message (an untyped length of at least 8, or a printable type byte and a length of at least 4), then demands the compatible shape and, in addition, one message of strong evidence at least:
| Message | Strong evidence |
|---|---|
StartupMessage | a known parameter (user, database, application_name, client_encoding, options, replication) with a value, and the final NUL |
SSLRequest, GSSENCRequest | exactly 8 bytes |
CancelRequest | a secret key of 4 to 256 bytes |
Query, Parse | a first word that is an SQL keyword |
CommandComplete | a tag that starts with an SQL keyword |
ErrorResponse, NoticeResponse | NUL-terminated fields, among them a message, a five-character SQLSTATE or a severity |
ParameterStatus | a name every server sends (server_version, client_encoding, scram_iterations, search_path...), the value possibly empty |
| Authentication | Ok, cleartext, Kerberos, SCM, GSS or SSPI at their fixed size, MD5 with its salt, the list of SASL mechanisms, SCRAM's server-first (r=…,s=…,i=…) and server-final (v=…) messages |
p | an MD5 hash (md5 and 32 hexadecimal digits), SCRAM's client-first (SCRAM-SHA-256, then n,,n=…,r=…) or client-final (c=…,r=…,p=…) message |
A cleartext password has no form to recognize: it is compatible, never a proof. Until 11.6.0 the blind probe also refused server replies whose ParameterStatus had an empty value (the application_name of a client that gave none) or a recent name (scram_iterations, search_path), and took only an AuthenticationSASL as proof; on the Zeek corpus, those real segments came out "Unknown".
The N of frame 6 of pcaps_exemple/protocols/postgresql/psql-login.pcap needs the port, or a declared one (tested):
#![allow(unused)] fn main() { #[test] fn a_one_byte_ssl_answer_needs_the_port() { let raw = hex::decode(POSTGRESQL_SSL_ANSWER_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("PostgreSQL")); // 5432 -> 35304 let payload = flow.transport.as_ref().unwrap().payload.unwrap(); assert_eq!(payload, b"N"); // TLS refused let packet = PostgreSqlPacket::try_from(payload).unwrap(); let [message] = packet.messages.as_slice() else { panic!("one message, got {}", packet.messages.len()); }; assert_eq!(message.message_type, PostgreSqlMessageType::SslResponse); assert_eq!(message.body, PostgreSqlMessageBody::SslResponse { accepted: false }); // One byte proves nothing: off port 5432 the blind probe leaves it. let moved = with_ports(&raw, 5433, 35304); assert_eq!(label(&parse(LinkType::ETHERNET, &moved).unwrap()), Some("Unknown")); // A declared port gets the port rule's probe. let config = ParseConfig::new().decode_as(5433, DecodeAsProtocol::PostgreSql); let flow = parse_with(LinkType::ETHERNET, &moved, &config).unwrap(); assert_eq!(label(&flow), Some("PostgreSQL")); } }
The SASLInitialResponse of frame 12 of the same capture is a p message of strong evidence (tested):
#![allow(unused)] fn main() { #[test] fn a_scram_p_message_is_proof_on_any_port() { let raw = hex::decode(POSTGRESQL_SASL_INITIAL_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("PostgreSQL")); // 35304 -> 5432 let payload = flow.transport.as_ref().unwrap().payload.unwrap(); assert_eq!(payload[0], b'p'); let packet = PostgreSqlPacket::try_from(payload).unwrap(); let [message] = packet.messages.as_slice() else { panic!("one message, got {}", packet.messages.len()); }; assert_eq!(message.message_type, PostgreSqlMessageType::PasswordOrSaslResponse); assert_eq!(message.length, 54); assert!(matches!(message.body, PostgreSqlMessageBody::Raw(_))); // The mechanism, the length of the initial response, then SCRAM's // client-first-message: no user name (psql sends it in the // StartupMessage), and the client's nonce. assert!(message.payload.starts_with(b"SCRAM-SHA-256\0")); assert!(message.payload.windows(8).any(|bytes| bytes == b"n,,n=,r=")); // The SCRAM form is strong evidence: the blind probe keeps the label // off port 5432. let moved = with_ports(&raw, 35304, 5433); assert_eq!(label(&parse(LinkType::ETHERNET, &moved).unwrap()), Some("PostgreSQL")); } }
Oracle: 276 segments
tests/postgresql_golden.rs runs the fourteen captures of pcaps_exemple/protocols/postgresql/ against tshark 4.6.6 without TCP reassembly, the view of a stateless parser (tools/postgresql_oracle.sh, frozen in tests/data/postgresql_tshark_oracle.tsv). Twelve are real psql sessions: loopback, a VM against AWS RDS, an application in containers, a Windows workstation. Two are negatives: HTTP and MySQL replayed on port 5432.
| What the test counts | Number |
|---|---|
| segments with a payload | 331 |
| of them, PostgreSQL | 276 |
| messages in those segments, with tshark's types and lengths, the 8 SSL answers included | 558 |
| segments still recognized by the blind probe off port 5432 | 262 |
| segments recognized on port 5432 only | 14 |
segments of the negatives that tshark labels pgsql | 6 |
| segments of the negatives that the crate labels | 0 |
The 14 segments that need the port are the ones without strong evidence, each alone in its segment: 8 SSL answers, 5 Terminate and 1 ReadyForQuery. Nine mutations of two real frames are rejected: lengths, protocol version, final NUL, type byte, truncation, trailing byte. The golden histogram counts 278 PostgreSQL labels: the 276 segments, and 2 retransmissions that tshark does not dissect.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- Most bodies. The decoder types every message and decodes the bodies of the main ones; the others stay
PostgreSqlMessageBody::Raw, thepmessages among them, which only the state of the authentication tells apart. - The state of the connection. Nothing follows the startup, the authentication or the extended query protocol from one segment to the next.
- A message cut by the segment. The messages must tile the segment: one that runs into the next segment makes the whole segment
"Unknown". - What follows an accepted
SSLRequest. The session continues in TLS and is labelled TLS: the crate does not decrypt.
PTP
Precision Time Protocol, IEEE 1588, added in 11.5.0 (#121) as the first protocol of the defense lot (#125): it synchronizes radars, combat systems and TSN avionics (802.1AS), and on the OT side the electrical substations (C37.238). The module is packet_parser::parse::application::protocols::ptp, whichever way the message travels.
Two carriers, two places in PacketFlow
PTP has two transports in the standard, and the crate follows both:
- UDP 319 and 320 (annex D over IPv4, annex E over IPv6): the datagram gets the application label
"PTP", like any other protocol of the dispatch table. - Raw Ethernet, EtherType
0x88F7(annex F), VLAN-tagged or not: there is no IP and no UDP, so the message is the internet layer,NetworkProtocol::Ptpon the internet page.
On UDP the rule is port-guarded: port_rule(ApplicationProtocol::Ptp, Guard::Udp, is_ptp_port, ProbeId::Ptp), 319 or 320 on either side. A blind probe is not possible here: the header has no magic, a messageType nibble does not tell PTP from arbitrary bytes, and a Delay_Req has exactly the shape of an SLPv1 header, which is how 829 of them were once labelled SRVLOC (#117). PTP on another UDP port is declared with ParseConfig::decode_as(port, DecodeAsProtocol::Ptp). The probe is PtpPacket::try_from_udp, stricter than the plain TryFrom: the message must fill the datagram, or all of it but the two bytes of annex E, the checksum correction field that UDP over IPv6 appends; anything else is UnexpectedTrailingBytes.
On Ethernet the internet dispatch calls PtpPacket::try_from and the flow gets an Internet with protocol_name "PTP", no addresses, payload_protocol None, and the decoded message in InternetDetails::Ptp; transport and application stay None. Ethernet pads short frames, so the bytes after messageLength are admitted and exposed in PtpV2Message::trailing. A versionPTP other than 1 or 2, or a reserved messageType, is not a corruption but an InternetError::UnsupportedProtocol, the outcome every 0x88F7 frame had before 11.5.0; a truncated or inconsistent message is InternetError::PtpError, reported in corrupted as PTP error: ….
Both carriers, on two frames of the same capture (tested):
#![allow(unused)] fn main() { #[test] fn ptp_is_a_label_on_udp_and_an_internet_layer_on_ethertype_88f7() { // Frame 25 of ptpv2.pcap: UDP 319 -> 319. The pipeline labels the // datagram; the protocol parser decodes it from the transport payload. let raw = hex::decode(ETHERNET_IPV4_UDP_PTP_SYNC_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "PTP"); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let PtpPacket::V2(sync) = PtpPacket::try_from_udp(payload).unwrap() else { panic!("expected a PTPv2 message"); }; assert_eq!(sync.header.message_type, 0); // Sync assert_eq!(sync.header.message_length, 44); assert_eq!(sync.header.sequence_id, 115); assert_eq!(sync.header.source_port_identity.port_number, 1); let PtpV2Body::Sync { origin_timestamp } = sync.body else { panic!("expected a Sync body, got {:?}", sync.body); }; assert_eq!(origin_timestamp.seconds, 1_169_232_217); assert_eq!(origin_timestamp.nanoseconds, 174_421_797); assert_eq!(sync.tlvs.iter().count(), 0); assert!(sync.trailing.is_empty()); // Frame 1 of the same capture: EtherType 0x88F7. No IP, no UDP: the // message is the internet layer, already decoded, and the flow has // neither a transport layer nor an application label. let raw = hex::decode(ETHERNET_PTP_PDELAY_REQ_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let internet = flow.internet.as_ref().unwrap(); assert_eq!(internet.protocol_name, "PTP"); assert!(internet.source.is_none() && internet.destination.is_none()); assert!(flow.transport.is_none() && flow.application.is_none()); assert!(flow.corrupted.is_none()); let Some(InternetDetails::Ptp(PtpPacket::V2(pdelay_req))) = &internet.details else { panic!("expected a decoded PTPv2 message in details"); }; assert_eq!(pdelay_req.header.message_type, 2); // Pdelay_Req assert_eq!(pdelay_req.header.sequence_id, 1118); assert!(matches!(pdelay_req.body, PtpV2Body::PdelayReq { .. })); assert!(pdelay_req.trailing.is_empty()); } }
The message
#![allow(unused)] fn main() { pub enum PtpPacket<'a> { V2(PtpV2Message<'a>), V1(PtpV1Message<'a>), } }
The version is the low nibble of byte 1: 2 for IEEE 1588-2008 and 2019, 1 for IEEE 1588-2002, whose 16-bit versionPTP happens to put a 1 in that very byte. Any other value is UnsupportedVersion. PtpPacket::version() and PtpPacket::sequence_id() answer without matching on the variant.
PTPv2: PtpV2Message
#![allow(unused)] fn main() { pub struct PtpV2Message<'a> { pub header: PtpV2Header, pub body: PtpV2Body, pub tlvs: PtpTlvs<'a>, // between the body and messageLength pub trailing: &'a [u8], // after messageLength: Ethernet padding, annex E bytes } }
PtpV2Header is the 34-byte common header of §13.3, decoded field by field:
| Bytes | Field | Note |
|---|---|---|
| 0 | major_sdo_id (high nibble), message_type (low nibble) | majorSdoId is transportSpecific in 1588-2008: 1 for 802.1AS |
| 1 | minor_version_ptp (high), version_ptp (low) | 2 |
| 2–3 | message_length | header, body and TLVs; what follows is trailing |
| 4 | domain_number | |
| 5 | minor_sdo_id | reserved in 1588-2008 |
| 6–7 | flags | two-step, unicast, timescale, leap flags… left as bits |
| 8–15 | correction_field | i64, nanoseconds × 2¹⁶ |
| 16–19 | message_type_specific | |
| 20–29 | source_port_identity | PortIdentity { clock_identity: [u8; 8], port_number: u16 } |
| 30–31 | sequence_id | |
| 32 | control_field | PTPv1 heritage, kept for compatibility |
| 33 | log_message_interval | i8 |
The body depends on message_type, and so does the minimum messageLength (§13.5 to §13.13): a declared length below it, or beyond the bytes received, is InvalidMessageLength { message_type, declared, minimum, available }.
messageType | PtpV2Body | Minimum | Fields |
|---|---|---|---|
0x0 | Sync | 44 | origin_timestamp |
0x1 | DelayReq | 44 | origin_timestamp |
0x2 | PdelayReq | 54 | origin_timestamp (then 10 reserved bytes) |
0x3 | PdelayResp | 54 | request_receipt_timestamp, requesting_port_identity |
0x8 | FollowUp | 44 | precise_origin_timestamp |
0x9 | DelayResp | 54 | receive_timestamp, requesting_port_identity |
0xA | PdelayRespFollowUp | 54 | response_origin_timestamp, requesting_port_identity |
0xB | Announce(PtpAnnounce) | 64 | origin_timestamp, current_utc_offset, grandmaster_priority1, grandmaster_clock_quality, grandmaster_priority2, grandmaster_identity, steps_removed, time_source |
0xC | Signaling | 44 | target_port_identity |
0xD | Management | 48 | target_port_identity, starting_boundary_hops, boundary_hops, action |
0x4–0x7, 0xE, 0xF | — | — | ReservedMessageType |
A PtpTimestamp is seconds: u64 (48 bits on the wire) and nanoseconds: u32; a ClockQuality is clock_class, clock_accuracy and offset_scaled_log_variance. The values are decoded, not interpreted: the crate computes no offset and keeps no clock state, as everywhere else it is stateless, one message at a time.
TLVs: a view, read on demand
Between the body and messageLength come the TLVs of §14.1, where the profiles put what makes them different (the organization extensions of C37.238, the path trace of 802.1AS, the management payload of ST 2059-2). PtpTlvs is a stateless view over those bytes: tlvs.iter() (or for tlv in message.tlvs) walks them from the start and yields Result<PtpTlv, PtpPacketParseError>, each PtpTlv { tlv_type: u16, value: &[u8] } borrowing the packet, the value raw. A truncated TLV comes out as TruncatedTlv { tlv_type, offset, needed, available } and the iterator stops there. The message decode never depends on the TLVs being valid: a message with a broken TLV area is still a message, which is what the oracle below does too. tlvs.as_bytes() gives the area whole.
PTPv1: PtpV1Message
IEEE 1588-2002 is recognized by its 40-byte header and left otherwise raw:
#![allow(unused)] fn main() { pub struct PtpV1Message<'a> { pub header: PtpV1Header<'a>, // versionPTP, versionNetwork, subdomain, messageType, // sourceCommunicationTechnology, sourceUuid, sourcePortId, // sequenceId, control, flags pub body: &'a [u8], } }
The validations are the ones of the 2002 text: versionPTP must be exactly 1 (InvalidV1VersionPtp), versionNetwork 1 (UnsupportedNetworkVersion), control one of Sync 0, Delay_Req 1, Follow_Up 2, Delay_Resp 3, Management 4 (ReservedControl), messageType consistent with it, 1 for the two event messages and 2 for the general ones (InconsistentMessageType), and the length fixed by control: 124 bytes for Sync and Delay_Req, 52 for Follow_Up, 60 for Delay_Resp, at least 40 for Management (InvalidV1Length { control, expected, actual }).
Validations
All of them are PtpPacketParseError, in packet_parser::errors::application::ptp:
| Error | When |
|---|---|
Truncated { expected, actual } | fewer bytes than the header, or than the body of the type, needs |
UnsupportedVersion(u8) | versionPTP is neither 1 nor 2 |
ReservedMessageType(u8) | PTPv2 messageType 0x4–0x7, 0xE or 0xF |
InvalidMessageLength { message_type, declared, minimum, available } | messageLength below the minimum of the type, or beyond the bytes received |
UnexpectedTrailingBytes { trailing } | try_from_udp only: bytes after messageLength other than the two of annex E |
TruncatedTlv { tlv_type, offset, needed, available } | from the TLV iterator, never from the message decode |
InvalidV1VersionPtp, UnsupportedNetworkVersion, ReservedControl, InconsistentMessageType, InvalidV1Length | PTPv1, see above |
What a failure means depends on the carrier. On UDP, the label is simply not given: the datagram is probed by the next rules and ends "Unknown", with nothing in corrupted, because a port is a hint and the payload may belong to something else. On 0x88F7 the EtherType has announced PTP, so the failure is a verdict: UnsupportedProtocol for an unknown version or type, a corrupted internet layer for the rest, exactly the distinction the internet page draws for every announced protocol.
Oracle: 3 328 messages, frame by frame
The golden test tests/ptp_golden.rs runs the eight captures of pcaps_exemple/protocols/ptp/ and compares every message with tshark 4.6.6, frozen in tests/data/ptp_tshark_oracle.tsv: version, type, length, domain, sequenceId, source identity and the list of TLV types. 3 217 PTPv2 and 4 PTPv1 messages on UDP, 107 PTPv2 at layer 2, one of them VLAN-tagged; the two ICMP messages that quote a PTP datagram are ICMP and excluded; no frame of the other corpus folders comes out PTP. The fuzz target parse_ptp runs nightly on the same parser.
| Capture | Messages | Equipment, profile | Origin |
|---|---|---|---|
ptpv2.pcap | 39 | Hirschmann, PTPv2, UDP and layer 2 | Wireshark wiki |
PTP_sync.pcap | 4 | Fujitsu Siemens, PTPv1 | Wireshark wiki |
ndpi_ptpv2.pcap | 14 | Symmetricom, PTPv2 over IPv6 | nDPI test corpus |
wireshark_6126_nodeb_startup.pcap | 3 179 | a 3G NodeB, telecom profile | Wireshark issue 6126 |
wireshark_14578_white_rabbit.pcap | 85 | Seven Solutions, White Rabbit, layer 2 | Wireshark issue 14578 |
wireshark_7694_c37_238.pcap | 1 | SEL, power profile IEEE C37.238, layer 2 | Wireshark issue 7694 |
wireshark_12264_st2059_mgt.pcap | 1 | Meinberg, SMPTE ST 2059-2 management | Wireshark issue 12264 |
wireshark_4761_802_1as.pcap | 7 | Marvell, IEEE 802.1AS (gPTP), layer 2 | Wireshark issue 4761 |
The NodeB capture is the one that taught the SRVLOC probe its language check: its 829 Delay_Req are the frames of #117.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- TLV values are not decoded: type and raw bytes only. The profiles (802.1AS, C37.238, ST 2059-2, telecom) are visible through
flags,major_sdo_idand the TLV types, not interpreted. - PTPv1 bodies stay raw; only the header is decoded.
- No clock state: no offset, no best-master decision, no pairing of a
Follow_Upwith itsSync. One message at a time, like the rest of the crate. - Other carriers of the annexes (DeviceNet, ControlNet, PROFINET) are not recognized; UDP 319/320 and
0x88F7are. - Security (annex K of 2008, clause 16 of 2019) is not checked; a secured message decodes like any other, its authentication TLV listed with the rest.
RADIUS
Remote Authentication Dial In User Service, RFC 2865, with accounting (RFC 2866) and dynamic authorization, Disconnect and CoA (RFC 5176): who connects, through which equipment, with what result. Decoded since 11.6.0 (#101, #156). The module is packet_parser::parse::application::protocols::radius: the header, then the list of attributes, each one borrowed from the datagram and, when the crate knows its type, named after the IANA registry, with accessors for the integers, IPv4 addresses and texts of the RFC and for the vendor id of a Vendor-Specific. Passwords stay encrypted: nothing in the crate knows the shared secret.
Detection: five ports, then any UDP port
Two rules of the dispatch table, 26 and 44, share one probe, ProbeId::Radius:
#![allow(unused)] fn main() { // among the port rules, after DIS port_rule(ApplicationProtocol::Radius, Guard::Udp, is_radius_udp_port, ProbeId::Radius), // 1812, 1813, 1645, 1646, 3799 // in the blind cascade, after DNP3, before BACnet/IP rule(ApplicationProtocol::Radius, Guard::Udp, ProbeId::Radius), }
is_radius_udp_port matches, on either side, 1812 and 1813, the IANA ports, 1645 and 1646, their historical numbers (the switch of radius.pcap still sends from 1645), and 3799, the port of RFC 5176. On UDP 1700, which tshark also dissects as RADIUS, the crate relies on the blind rule. The probe is RadiusPacket::try_from(payload).is_ok(), run on the whole payload, as every probe but the four text ones since 11.7.0 (#185): the declared length is compared with the real datagram. It accepts a datagram only if:
- the code is one of the fourteen of RFC 2865, 2866 and 5176;
- the declared length is between 20 and 4096 and equals the datagram;
- the attributes tile the rest exactly: none shorter than its 2-byte header, none past the end, no byte left over.
RFC 2865 §3 tells a receiver to treat the bytes after Length as padding and ignore them. The crate requires the length to be the datagram's instead, its reason being that a decoder tolerating trailing bytes would make a poor blind probe. With that, the same probe runs blind on any UDP datagram that no earlier rule has claimed, and there is no DecodeAsProtocol variant for RADIUS: a server on another port is recognized anyway. Both rules are Guard::Udp; RADIUS over TCP or TLS is not probed.
Since the two rules share the probe, a datagram on 1812 that fails it is not probed again by the blind rule: it goes on down the table, usually to "Unknown". A refusal never fills corrupted: on UDP a port is a hint, not an announcement, as for PTP. Every packet of the corpus has 1812 on one side; the blind route is checked by moving frame 1 of radius.pcap to other ports, and the test shows what the probe looks at and what it does not (tested):
#![allow(unused)] fn main() { #[test] fn radius_is_recognized_off_its_ports_and_refused_when_altered() { // Frame 1 moved to UDP 40000 -> 40001: the blind rule recognizes it. let mut raw = hex::decode(RADIUS_ACCESS_REQUEST_HEX).unwrap(); raw[34..38].copy_from_slice(&[0x9c, 0x40, 0x9c, 0x41]); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "RADIUS"); // The authenticator and the values are not checked: nothing here knows // the shared secret. let start = raw.len() - 139; // where the RADIUS header starts let mut values = raw.clone(); values[start + 4] ^= 0xff; // first byte of the authenticator values[start + 22] ^= 0xff; // first byte of the NAS-IP-Address value let flow = parse(LinkType::ETHERNET, &values).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "RADIUS"); // The structure is checked: an unknown code, a length that is not the // datagram's, attributes that no longer tile it (a NAS-IP-Address one // byte longer makes the next attribute start on a length byte). for (offset, value, error) in [ (0, 6, RadiusParseError::UnknownCode(6)), (3, 0x8a, RadiusParseError::LengthMismatch { declared: 138, actual: 139 }), (21, 7, RadiusParseError::AttributeTooShort { attribute_type: 6, length: 0 }), ] { let mut altered = raw.clone(); altered[start + offset] = value; assert_eq!(RadiusPacket::try_from(&altered[start..]), Err(error)); let flow = parse(LinkType::ETHERNET, &altered).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "Unknown"); assert!(flow.corrupted.is_none()); } } }
The packet
#![allow(unused)] fn main() { pub struct RadiusPacket<'a> { pub code: u8, pub kind: RadiusCode, // always known: the decoder refuses other codes pub identifier: u8, // pairs a request and its response pub length: u16, // equal to the datagram pub authenticator: [u8; 16], // as on the wire pub attributes: Vec<RadiusAttribute<'a>>, } }
| Bytes | Field | Note |
|---|---|---|
| 0 | code, kind | one of the fourteen codes below |
| 1 | identifier | |
| 2–3 | length | 20 to 4096 (RFC 2865 §3), header included |
| 4–19 | authenticator | the Request Authenticator, or a Response Authenticator computed with the shared secret: copied, not verified |
| 20– | attributes | type, length, value, up to length |
| Code | RadiusCode | RFC |
|---|---|---|
| 1 | AccessRequest | 2865 |
| 2 | AccessAccept | 2865 |
| 3 | AccessReject | 2865 |
| 4 | AccountingRequest | 2866 |
| 5 | AccountingResponse | 2866 |
| 11 | AccessChallenge | 2865 |
| 12 | StatusServer | 2865 |
| 13 | StatusClient | 2865 |
| 40 | DisconnectRequest | 5176 |
| 41 | DisconnectAck | 5176 |
| 42 | DisconnectNak | 5176 |
| 43 | CoaRequest | 5176 |
| 44 | CoaAck | 5176 |
| 45 | CoaNak | 5176 |
The structs and enums of the module are #[non_exhaustive], and RadiusCode::from_code is public. The attribute list is the only part that allocates: a Vec whose initial capacity is at most 16, and never more than the bytes left could hold; past 16 attributes it grows like any Vec. An Access-Request from a switch, decoded attribute by attribute (tested):
#![allow(unused)] fn main() { #[test] fn radius_access_request_of_a_switch() { let raw = hex::decode(RADIUS_ACCESS_REQUEST_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "RADIUS"); let transport = flow.transport.as_ref().unwrap(); assert_eq!((transport.source_port, transport.destination_port), (Some(1645), Some(1812))); let packet = RadiusPacket::try_from(transport.payload.unwrap()).unwrap(); assert_eq!(packet.kind, RadiusCode::AccessRequest); assert_eq!((packet.code, packet.identifier, packet.length), (1, 5, 139)); assert_eq!(packet.authenticator[..4], [0xec, 0xfe, 0x3d, 0x2f]); // Ten attributes in wire order, each value borrowed from the datagram. let types: Vec<u8> = packet.attributes.iter().map(|a| a.attribute_type).collect(); assert_eq!(types, [4, 5, 61, 1, 30, 31, 6, 12, 79, 80]); assert_eq!(packet.attributes[0].kind, Some(AttributeType::NasIpAddress)); // The first attribute of a type, read through the accessor that fits. let nas = packet.attribute(AttributeType::NasIpAddress).and_then(RadiusAttribute::as_ipv4); assert_eq!(nas, Some(Ipv4Addr::new(10, 0, 0, 1))); let port = packet.attribute(AttributeType::NasPort).and_then(RadiusAttribute::as_u32); assert_eq!(port, Some(50012)); let user = packet.attribute(AttributeType::UserName).and_then(RadiusAttribute::as_text); assert_eq!(user, Some("John.McGuirk")); let station = packet .attribute(AttributeType::CallingStationId) .and_then(RadiusAttribute::as_text); assert_eq!(station, Some("00-14-22-E9-54-5E")); let mtu = packet.attribute(AttributeType::FramedMtu).and_then(RadiusAttribute::as_u32); assert_eq!(mtu, Some(1500)); // EAP and the Message-Authenticator stay bytes; an accessor that does // not fit the value answers None. let eap = packet.attribute(AttributeType::EapMessage).unwrap(); assert_eq!((eap.length, eap.value.len()), (19, 17)); assert_eq!(eap.as_u32(), None); let authenticator = packet.attribute(AttributeType::MessageAuthenticator).unwrap(); assert_eq!(authenticator.value.len(), 16); assert_eq!(packet.attribute(AttributeType::VendorSpecific), None); } }
The header alone is a valid packet: the Access-Reject of a capture taken on the loopback interface, read from a BSD loopback frame (tested):
#![allow(unused)] fn main() { #[test] fn radius_access_reject_without_attributes_on_loopback() { // Captured on the loopback interface: LINKTYPE_NULL, then IPv4 and UDP. let raw = hex::decode(LOCALHOST_ACCESS_REJECT_HEX).unwrap(); let flow = parse(LinkType::NULL, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "RADIUS"); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = RadiusPacket::try_from(payload).unwrap(); assert_eq!(packet.kind, RadiusCode::AccessReject); assert_eq!((packet.identifier, packet.length), (43, 20)); assert!(packet.attributes.is_empty()); // the header alone is a packet } }
Attributes
#![allow(unused)] fn main() { pub struct RadiusAttribute<'a> { pub attribute_type: u8, pub kind: Option<AttributeType>, // None for a type the crate does not name pub length: u8, // declared, header included pub value: &'a [u8], // length - 2 bytes, borrowed } }
AttributeType names every assigned type of the IANA registry RADIUS Attribute Types, 192 of them: 1 to 190 except 17, 21, 54 and 93, which are unassigned, and the extended types 241 to 246. Types 126 to 190 have been named since 11.7.0 (#192): Operator-Name and location (RFC 5580), management (RFC 5607), PKM (RFC 5904), DS-Lite (RFC 6519), PMIPv6 (RFC 6572), EAP-Lower-Layer (RFC 6677), GSS-EAP (RFC 7055), IPv6 (RFC 6911, RFC 6930) and IEEE 802 (RFC 7268); 11.6.0 named 127 types and returned None for them. Code 191, the experimental 192 to 223, the implementation-specific 224 to 240 and the reserved 247 to 255 are None: any such type is kept, with kind: None and its value. AttributeType::from_code is public.
The variants carry the registry's names, in CamelCase (173, IPv6-6rd-Configuration, is Ipv6SixRdConfiguration), with eight exceptions. 89, 101 and 241 to 246 carry the names of their RFC: ChargeableUserIdentity (CUI in the registry), ErrorCause ("Error-Cause Attribute"), ExtendedType1 to ExtendedType4, LongExtendedType1 and LongExtendedType2 (Extended-Attribute-1 to -6). 124 and 125 carried until 12.0.0 the names of two Diameter AVPs, MipHomeAgentAddress and MipHomeAgentHost, which do not exist in RADIUS: 124 is MIP6-Feature-Vector, a field of 64 flags, not an address, and 125 MIP6-Home-Link-Prefix, a prefix length and an IPv6 prefix, not a host name (RFC 5447). The registry's name of 89, 124, 125, 173 and 241 to 246 is a search alias in the rustdoc.
11.7.0 deprecated those two variants (#191) and gave the registry's names to two associated constants equal to them. 12.0.0 renames the variants in place, at the same position: they are AttributeType::Mip6FeatureVector and AttributeType::Mip6HomeLinkPrefix, the constants are gone, and code written with them compiles unchanged. from_code(124) and from_code(125) return the same values as before, and {:?} now prints the registry's names. The old names no longer compile.
No capture of the corpus carries a type above 95. A packet built by hand, with the two types of RFC 5447 and an Operator-Name (tested):
#![allow(unused)] fn main() { #[test] fn radius_types_124_and_125_by_their_registry_names() { // An Access-Request built by hand: no capture of the corpus carries a // type above 95. The header, then four attributes. let mut bytes = vec![1, 7, 0, 0]; // code, identifier, length (set below) bytes.extend_from_slice(&[0; 16]); // request authenticator, not checked // 124, MIP6-Feature-Vector: 64 flags, here the lowest one. bytes.extend_from_slice(&[124, 10, 0, 0, 0, 0, 0, 0, 0, 1]); // 125, MIP6-Home-Link-Prefix: a prefix length, then 2001:db8:1::. bytes.extend_from_slice(&[125, 19, 64, 0x20, 0x01, 0x0d, 0xb8, 0, 1]); bytes.extend_from_slice(&[0; 10]); // 126, Operator-Name, named since 11.7.0. bytes.extend_from_slice(&[126, 14]); bytes.extend_from_slice(b"1example.net"); // 192, the first of the experimental types. bytes.extend_from_slice(&[192, 3, 0xff]); let length = u16::try_from(bytes.len()).unwrap(); bytes[2..4].copy_from_slice(&length.to_be_bytes()); let packet = RadiusPacket::try_from(bytes.as_slice()).unwrap(); assert_eq!((packet.kind, packet.length), (RadiusCode::AccessRequest, 66)); // The constants are patterns, like the variants they stand for. let names: Vec<&str> = packet .attributes .iter() .map(|attribute| match attribute.kind { Some(AttributeType::Mip6FeatureVector) => "MIP6-Feature-Vector", Some(AttributeType::Mip6HomeLinkPrefix) => "MIP6-Home-Link-Prefix", Some(AttributeType::OperatorName) => "Operator-Name", Some(_) => "another named type", None => "not named", }) .collect(); assert_eq!( names, ["MIP6-Feature-Vector", "MIP6-Home-Link-Prefix", "Operator-Name", "not named"] ); // They are arguments too. The values stay bytes, read by the caller. let features = packet.attribute(AttributeType::Mip6FeatureVector).unwrap(); assert_eq!(u64::from_be_bytes(features.value.try_into().unwrap()), 1); let home = packet.attribute(AttributeType::Mip6HomeLinkPrefix).unwrap(); let prefix: [u8; 16] = home.value[1..].try_into().unwrap(); assert_eq!((home.value[0], Ipv6Addr::from(prefix)), (64, "2001:db8:1::".parse().unwrap())); let operator = packet.attribute(AttributeType::OperatorName); assert_eq!(operator.and_then(RadiusAttribute::as_text), Some("1example.net")); // from_code(124) is the same value as in 11.6.0; since 12.0.0 the // variant carries the registry's name, and {:?} prints it. assert_eq!(AttributeType::from_code(124), Some(AttributeType::Mip6FeatureVector)); assert_eq!(format!("{:?}", AttributeType::Mip6FeatureVector), "Mip6FeatureVector"); assert_eq!(format!("{:?}", AttributeType::Mip6HomeLinkPrefix), "Mip6HomeLinkPrefix"); // Every assigned type is named: 1 to 190 but four, and 241 to 246. let named = (0..=255).filter(|&code| AttributeType::from_code(code).is_some()); assert_eq!(named.count(), 192); for code in [17, 21, 54, 93, 191, 192, 223, 224, 240, 247, 255] { assert_eq!(AttributeType::from_code(code), None); } assert_eq!(AttributeType::from_code(190), Some(AttributeType::WlanRfBand)); } }
Four accessors read a value:
| Method | Returns | Some when |
|---|---|---|
as_u32() | Option<u32> | the value is 4 bytes: NAS-Port, Service-Type, Acct-Status-Type… |
as_ipv4() | Option<Ipv4Addr> | the value is 4 bytes: NAS-IP-Address, Framed-IP-Address… |
as_text() | Option<&'a str> | the value is UTF-8: User-Name, NAS-Identifier, Reply-Message… |
vendor() | Option<(u32, &'a [u8])> | the attribute is a Vendor-Specific (26) whose value has at least 4 bytes: the vendor id, an IANA Private Enterprise Number, then the bytes the vendor defines |
The first three do not look at the type: as_u32 reads any 4-byte value, and choosing the accessor the RFC gives an attribute is the caller's job. RadiusPacket::attribute(kind) returns the first attribute of a type. An attribute holds at most 253 bytes of value, its length being one byte, so a longer EAP packet is spread over several EAP-Message attributes, which the caller reads by walking attributes: frame 36722 of the Ultimate PCAP, an Access-Challenge of 1 068 bytes, carries four of them, 255, 255, 255 and 247 bytes long with their 2-byte headers. An Access-Accept over IPv6 with three Microsoft attributes (tested):
#![allow(unused)] fn main() { #[test] fn radius_access_accept_with_microsoft_vendor_attributes() { // Over IPv6 this time: the rule only looks at UDP. let raw = hex::decode(ULTIMATE_ACCESS_ACCEPT_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.internet.as_ref().unwrap().protocol_name, "IPv6"); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "RADIUS"); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = RadiusPacket::try_from(payload).unwrap(); assert_eq!(packet.kind, RadiusCode::AccessAccept); assert_eq!((packet.identifier, packet.length), (22, 96)); // answers request 22 let reply = packet.attribute(AttributeType::ReplyMessage); assert_eq!(reply.and_then(RadiusAttribute::as_text), Some("Hello, bob")); // Three Vendor-Specific attributes: the vendor id, then the bytes the // vendor defines, which the crate does not decode. let vendors: Vec<(u32, &[u8])> = packet.attributes.iter().filter_map(RadiusAttribute::vendor).collect(); assert_eq!(vendors.len(), 3); assert!(vendors.iter().all(|(id, _)| *id == 311)); // Microsoft // Vendor type 7, length 6, value 1: MS-MPPE-Encryption-Policy, for tshark. assert_eq!(vendors[1].1, &[7, 6, 0, 0, 0, 1]); // vendor() answers only on a Vendor-Specific attribute. assert_eq!(packet.attributes[0].kind, Some(AttributeType::ReplyMessage)); assert_eq!(packet.attributes[0].vendor(), None); } }
Validations
All of them are RadiusParseError, in packet_parser::errors::application::radius:
| Error | When |
|---|---|
Truncated { expected, actual } | fewer than the 20 bytes of the header |
UnknownCode(u8) | a code outside the fourteen above |
InvalidLength(u16) | a declared length below 20 or above 4096 |
LengthMismatch { declared, actual } | a declared length other than the datagram's |
AttributeTooShort { attribute_type, length } | an attribute length of 0 or 1, shorter than its own header |
AttributeOverflow { attribute_type, needed, available } | an attribute that runs past the end, or a single byte left after the last attribute |
In the pipeline, every one of them means the same thing: the label is not given, as the detection section shows.
Oracle: 95 packets, attribute by attribute
The golden test tests/radius_golden.rs runs the two captures of pcaps_exemple/protocols/radius/ and The-Ultimate-PCAP.pcapng, read in place, and compares every packet with tshark 4.6.6, frozen in tests/data/radius_tshark_oracle.tsv by tools/radius_oracle.sh: ports, code, identifier, length, authenticator, the types and lengths of the attributes, the vendor ids of the Vendor-Specific.
| Capture | Packets | Content | Origin |
|---|---|---|---|
protocols/radius/radius.pcap | 4 | a Cisco switch, from port 1645, authenticates John.McGuirk in EAP: Access-Request, Access-Challenge, Access-Request, Access-Accept | Zeek test corpus, BSD 3-clause |
protocols/radius/radius_localhost.pcap | 19 | loopback traffic, 127.0.0.1 to 127.0.0.1, LINKTYPE_NULL (a classic pcap does not record the interface): a client that tries EAP, PAP and CHAP from seven ephemeral ports, one per authentication; eleven Access-Requests to port 1812 carrying EAP-Message, User-Password or CHAP-Password, and their two Access-Challenge, four Access-Accept and two Access-Reject | Zeek test corpus, BSD 3-clause |
The-Ultimate-PCAP.pcapng | 72 of 51 328 frames | December 2022, a switch and VMware machines over IPv4 and IPv6: EAP-PEAP and EAP-TTLS exchanges, Microsoft Vendor-Specific attributes | Johannes Weber, The Ultimate PCAP |
Over the 95: 49 Access-Request, 26 Access-Challenge, 18 Access-Accept and 2 Access-Reject, carrying 28 Vendor-Specific attributes, all of Microsoft (311). None of the other 51 256 frames of the Ultimate PCAP is labelled RADIUS. A second test moves frame 1 of radius.pcap to ports 40000 and 40001, then alters the code (to 6, outside the fourteen), the length and the length of the first attribute (twice): each is refused and loses the label, while an altered authenticator and an altered attribute value keep it.
A run of the 11.6.0 pipeline over the 386 403 frames that the crate's test reader gets from the captures tracked under pcaps_exemple/ gives the label "RADIUS" to exactly the 265 packets tshark dissects as RADIUS: these 95, and 170 more on port 1812 that the golden test does not cover, in vlan0--packet-capture CAPWAP…cap, a 2016 test-network capture at the root of pcaps_exemple/ whose origin is not documented. The 170 and the 72 of the Ultimate PCAP are the 242 RADIUS packets that, according to the CHANGELOG, leave "Unknown" on the 11.5.0 corpus. The fuzz target parse_radius runs nightly, on its input and on mutations of three real packets: whatever it decodes must have the input's length, between 20 and 4096, and attributes that tile it exactly, each value length - 2 bytes inside the input, vendor() answering only on a Vendor-Specific.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- The shared secret: neither authenticator nor the Message-Authenticator is verified, and User-Password, Tunnel-Password or the keys a vendor attribute carries stay the bytes of the wire.
- EAP is not decoded: an EAP-Message value is raw bytes, and an EAP packet spread over several attributes is not reassembled.
- Vendor attributes:
vendor()gives the vendor id and the vendor's bytes; their sub-attributes are not split. - Other value types: no accessor for IPv6 addresses (NAS-IPv6-Address, in the Ultimate PCAP), and the extended types 241 to 246 are named but not unpacked.
- No state: a response is not matched with its request, and the three identical Access-Requests of
radius_localhost.pcap, a retransmission, are three packets. One datagram at a time, as in the rest of the crate. - Codes no capture exercises: none of the 265 RADIUS packets of the repository's captures is an accounting, Status-Server, Status-Client, Disconnect or CoA packet; codes 4, 5, 12, 13 and 40 to 45 follow the RFCs.
RDP
Remote Desktop Protocol, MS-RDPBCGR, added in 11.6.0 (#100). It rides on the stack that 10.0.0 tooled for S7comm, TPKT (RFC 1006) and COTP X.224 (RFC 905), with T.125 MCS above it. Segment by segment, the decoder reads what a stateless parser can see of a connection: the X.224 connection, where the client sends its cookie and the security protocols it offers and the server selects one or refuses, then the MCS PDUs that follow when standard RDP security is kept. Module: packet_parser::parse::application::protocols::rdp.
Detection: port 3389, then TLS
The rule is port-guarded, TCP 3389 (IANA ms-wbt-server) on either side:
#![allow(unused)] fn main() { port_rule(ApplicationProtocol::Rdp, Guard::Tcp, is_rdp_tcp_port, ProbeId::Rdp), // 3389 }
A blind probe is ruled out because none of the three layers is RDP's own: TPKT, COTP and MCS are also the stack of T.120 and of ISO over TCP. A server on another port is declared with ParseConfig::decode_as(port, DecodeAsProtocol::Rdp), which runs the same probe under the same TCP guard (Decode As). The probe is RdpPacket::try_from, on the whole segment. classify_payload called with no port (None, None) never answers "RDP".
After a TLS or CredSSP negotiation, the segments are labelled TLS. Once the server has selected TLS or CredSSP, the connection carries TLS records. Their first byte is a content type (0x16 for a handshake) where TPKT wants version 3, so the RDP probe refuses them and the blind TLS rule further down the table takes them. That is the decision of the issue, tested on rdp-to-ssl.pcap: a stateless parser sees TLS records and names them, and nothing ties them back to the RDP connection they belong to.
The Connection Request of frame 6 of rdp-x509.pcap, on its port, moved to another one, then on that port declared (tested):
#![allow(unused)] fn main() { #[test] fn rdp_on_port_3389_and_the_connection_request() { let raw = hex::decode(RDP_COOKIE_REQUEST_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "RDP"); // The label is a classification; RdpPacket is the decode. let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = RdpPacket::try_from(payload).unwrap(); assert_eq!(packet.pdus.len(), 1); // one TPKT in the segment assert!(!packet.truncated); let pdu = &packet.pdus[0]; assert_eq!(pdu.tpkt_length, 47); assert_eq!(pdu.cotp.pdu_type, CotpPduType::ConnectionRequest); assert_eq!(pdu.cotp.length_indicator, 42); assert_eq!((pdu.cotp.dst_ref, pdu.cotp.src_ref), (Some(0), Some(0))); assert_eq!(pdu.cotp.class, Some(0)); let RdpPayload::ConnectionRequest { token, negotiation } = &pdu.payload else { panic!("expected a Connection Request, got {:?}", pdu.payload); }; assert_eq!(*token, Some(&b"Cookie: mstshash=JOHN-PC "[..])); // without CR LF assert_eq!(pdu.payload.cookie_user(), Some("JOHN-PC ")); let negotiation = negotiation.expect("a negotiation request"); assert_eq!(negotiation.requested_protocols, 0); assert!(negotiation.standard_security_only()); // Bytes 36-37 are the TCP destination port (Ethernet, IPv4 without // options). On 3390 the port guard stays closed... let mut moved = raw.clone(); moved[36..38].copy_from_slice(&3390u16.to_be_bytes()); let flow = parse(LinkType::ETHERNET, &moved).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "Unknown"); // ... until the caller declares the port. let config = ParseConfig::new().decode_as(3390, DecodeAsProtocol::Rdp); let flow = parse_with(LinkType::ETHERNET, &moved, &config).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "RDP"); } }
The segment: TPKTs
#![allow(unused)] fn main() { pub struct RdpPacket<'a> { pub pdus: Vec<RdpPdu<'a>>, /// The last TPKT announces more than the segment holds. pub truncated: bool, } pub struct RdpPdu<'a> { /// Declared TPKT length, header included. pub tpkt_length: u16, pub cotp: X224Tpdu, pub payload: RdpPayload<'a>, } pub struct X224Tpdu { pub length_indicator: u8, pub pdu_type: CotpPduType, /// CR and CC only. pub dst_ref: Option<u16>, pub src_ref: Option<u16>, pub class: Option<u8>, /// DT only: last TPDU of the TSDU. pub end_of_tsdu: Option<bool>, } }
Every type of the module is #[non_exhaustive]: a match on RdpPayload or McsPduType needs a _ arm.
RdpPacket::try_from reads TPKTs back to back until the end of the segment, and the segment is RDP only if every one of them decodes. The last one may announce more bytes than the segment holds, because TCP cut it: as long as the headers the decoder reads are complete, it is decoded on what is there and truncated is set. Its continuation, in the next segment, has no header of its own and is not RDP: the crate does not reassemble, and tshark without reassembly calls those bytes data. TCP cuts 16 TPKTs of the corpus in two, and the 12 that start their segment are decoded that way: 11 Send Data Requests of 1 421 bytes whose first segment holds 1 260, and a Connect-Response of 1 405 bytes whose first segment holds 1 398. The other 4 start in the middle of a segment, after the end of the previous TPKT (frames 69, 71, 73 and 74 of rdp-proprietary-encryption.pcap): those segments do not start with a TPKT, and none of their bytes is decoded.
The TPKT header and the fixed part of the TPDU, on the Connection Request of frame 6 of rdp-x509.pcap (offsets in the TCP payload):
| Bytes | Field | Frame 6 | Check |
|---|---|---|---|
| 0 | TPKT version | 3 | must be 3, else InvalidTpkt |
| 1 | TPKT reserved | 0 | must be 0, else InvalidTpkt |
| 2–3 | tpkt_length, big-endian, header included | 47 | at least 7, else TpktTooShort |
| 4 | length_indicator | 42 | |
| 5 | pdu_type: high nibble E for CR, D for CC (the low nibble is the credit), F0 for DT | E0, CR | any other TPDU is UnexpectedTpdu |
| 6–7 | dst_ref (CR and CC) | 0 | |
| 8–9 | src_ref (CR and CC) | 0 | |
| 10 | class (CR and CC) | 0 | |
| 11… | X.224 user data, as far as the length indicator goes: the token, then the negotiation | see below |
In a DT, byte 6 holds the EOT bit (0x80), end_of_tsdu, and the MCS PDU starts length_indicator + 1 bytes into the TPDU, at byte 7 for the usual length indicator of 2.
MS-RDPBCGR counts the token and the negotiation of a CR or a CC in the length indicator, where the crate's generic COTP parser, cotp::CotpHeader (the module was misspelt copt until 12.0.0), would read variable-part parameters. The RDP decoder therefore reads the fixed part itself and reuses only CotpPduType.
The connection: Connection Request and Confirm
#![allow(unused)] fn main() { pub enum RdpPayload<'a> { /// X.224 Connection Request of the client. ConnectionRequest { /// `Cookie: mstshash=<user>` or a routing token, without its CR LF. token: Option<&'a [u8]>, negotiation: Option<NegotiationRequest>, }, /// X.224 Connection Confirm of the server. ConnectionConfirm { negotiation: Option<NegotiationResponse>, }, /// An MCS PDU in a Data TPDU. Mcs(McsPdu<'a>), } pub struct NegotiationRequest { pub flags: u8, /// Bits: 1 TLS, 2 CredSSP, 4 RDSTLS, 8 CredSSP with Early User /// Authorization Result, 0x10 RDS-AAD-Auth; zero for standard RDP /// security only. pub requested_protocols: u32, /// The correlationId of the correlation info, when the flags announce /// one and it follows the request. pub correlation_id: Option<[u8; 16]>, } pub enum NegotiationResponse { Accepted { flags: u8, selected_protocol: u32 }, Failure { failure_code: u32 }, } }
The X.224 user data of a Connection Request is a token, then a negotiation request, both optional. The token is everything before the first CR LF, kept raw: Cookie: mstshash=<user> from the usual client, or a routing token. RdpPayload::cookie_user() returns the user of a cookie as a &str, and None for anything else. After the token comes nothing, or an 8-byte negotiation request, which a correlation info may follow; anything that starts with a byte other than the request's type 0x01 is UnexpectedX224Data. The user data of a Connection Confirm is empty, or the server's response or failure, in the same 8-byte structure, with nothing after it:
| Byte | Field | Note |
|---|---|---|
| 0 | type | 0x01 request (in a CR), 0x02 response or 0x03 failure (in a CC) |
| 1 | flags | kept raw, not read for a failure |
| 2–3 | length, little-endian | must be 8, else InvalidNegotiation |
| 4–7 | requested_protocols, selected_protocol or failure_code | u32, little-endian |
Only the length field gives InvalidNegotiation. A structure that stops before its eighth byte, because TCP cut the TPKT or the length indicator ends early, is Truncated { expected: 8, .. }. Bytes after the structure are UnexpectedX224Data(n), n being their count, unless the request announces a correlation info (see the validations).
The protocols are bits (MS-RDPBCGR §2.2.1.1.1), and NegotiationRequest has a method for each but the last:
| Value | Security protocol | Method |
|---|---|---|
| 0 | standard RDP security only | standard_security_only() |
0x1 | TLS | tls() |
0x2 | CredSSP | credssp() |
0x4 | RDSTLS | rdstls() |
0x8 | CredSSP with Early User Authorization Result | credssp() |
0x10 | RDS-AAD-Auth | none: the bit stays in requested_protocols |
selected_protocol holds one of these values. The flags and failure_code stay numbers that the crate does not name, except the request flag 0x08, which correlation_info_present() reads. Since 11.7.0 the crate documents them (#188), after MS-RDPBCGR §2.2.1.1.1, §2.2.1.2.1 and §2.2.1.2.2:
| Field | Value | Meaning |
|---|---|---|
request flags | 0x01 | RESTRICTED_ADMIN_MODE_REQUIRED: a logon without credentials over CredSSP |
0x02 | REDIRECTED_AUTHENTICATION_MODE_REQUIRED: a logon without credentials, the authentication redirected over CredSSP (Remote Credential Guard) | |
0x08 | CORRELATION_INFO_PRESENT: a correlation info follows the request | |
response flags | 0x01 | EXTENDED_CLIENT_DATA_SUPPORTED |
0x02 | DYNVC_GFX_PROTOCOL_SUPPORTED (MS-RDPEGFX) | |
0x04 | NEGRSP_FLAG_RESERVED, which the client ignores | |
0x08 | RESTRICTED_ADMIN_MODE_SUPPORTED | |
0x10 | REDIRECTED_AUTHENTICATION_MODE_SUPPORTED | |
failure_code | 1 | SSL_REQUIRED_BY_SERVER: TLS or CredSSP required |
| 2 | SSL_NOT_ALLOWED_BY_SERVER: standard RDP security only | |
| 3 | SSL_CERT_NOT_ON_SERVER: no valid certificate on the server | |
| 4 | INCONSISTENT_FLAGS: the requested protocols contradict the one already in force | |
| 5 | HYBRID_REQUIRED_BY_SERVER: CredSSP required | |
| 6 | SSL_WITH_USER_AUTH_REQUIRED_BY_SERVER: TLS with a client certificate required | |
| 7 | ENTRA_AUTH_REQUIRED_BY_SERVER: Entra ID authentication by RDS-AAD-Auth required; tshark 4.6.6 does not name it |
The Connection Confirm of frame 9 of rdp-no-cookie-mstshash.pcap sets all five response flags, 0x1f. The negotiation is where the connection forks: standard security keeps TPKT and MCS on the wire, TLS or CredSSP turns the rest of it into TLS records. A refusal and a CredSSP selection, on real frames of two captures (tested):
#![allow(unused)] fn main() { #[test] fn the_negotiation_decides_what_follows() { // A client offers TLS (rdp-proprietary-encryption.pcap, frame 4)... let raw = hex::decode(RDP_TLS_REQUEST_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let segment = flow.transport.as_ref().unwrap().payload.unwrap(); let request = RdpPacket::try_from(segment).unwrap(); let payload = &request.pdus[0].payload; assert_eq!(payload.cookie_user(), Some("FTBCO\\A70")); let RdpPayload::ConnectionRequest { negotiation: Some(offer), .. } = payload else { panic!("expected a negotiation request, got {payload:?}"); }; assert_eq!(offer.requested_protocols, 0x0000_0001); assert!(offer.tls() && !offer.credssp() && !offer.rdstls()); // ... and the server refuses it (frame 5): failure code 2, which // tshark names "TLS not allowed by server". let raw = hex::decode(RDP_NEGOTIATION_FAILURE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "RDP"); let segment = flow.transport.as_ref().unwrap().payload.unwrap(); let confirm = RdpPacket::try_from(segment).unwrap(); assert_eq!(confirm.pdus[0].cotp.pdu_type, CotpPduType::ConnectionConfirm); assert_eq!(confirm.pdus[0].cotp.src_ref, Some(0x1234)); assert_eq!( confirm.pdus[0].payload, RdpPayload::ConnectionConfirm { negotiation: Some(NegotiationResponse::Failure { failure_code: 2 }) } ); // Another server selects CredSSP (rdp-to-ssl.pcap, frame 6)... let raw = hex::decode(RDP_CREDSSP_SELECTED_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let segment = flow.transport.as_ref().unwrap().payload.unwrap(); let confirm = RdpPacket::try_from(segment).unwrap(); assert_eq!( confirm.pdus[0].payload, RdpPayload::ConnectionConfirm { negotiation: Some(NegotiationResponse::Accepted { flags: 0x01, selected_protocol: 2 }) } ); // ... so the client's next segment with a payload (frame 8) is a TLS // record: on port 3389 it fails the TPKT check, and the blind TLS rule // labels it. let raw = hex::decode(RDP_CLIENT_HELLO_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let transport = flow.transport.as_ref().unwrap(); assert_eq!(transport.destination_port, Some(3389)); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "TLS"); assert_eq!( RdpPacket::try_from(transport.payload.unwrap()), Err(RdpParseError::InvalidTpkt { version: 0x16, reserved: 0x03 }) ); } }
The correlation info
A client may append to its negotiation request a 36-byte RDP_NEG_CORRELATION_INFO (MS-RDPBCGR §2.2.1.1.2), which it announces with the request flag 0x08, CORRELATION_INFO_PRESENT. The decoder has read it since 11.7.0 (#187). In 11.6.0, a Connection Request that carried one was refused with InvalidNegotiation ("declares 8 bytes, not 8"), and the segment came out "Unknown" on port 3389, its cookie and requested protocols lost. Offsets from the end of the request:
| Bytes | Field | Note |
|---|---|---|
| 0 | type | 0x06, else InvalidCorrelationInfo |
| 1 | flags | not read |
| 2–3 | length, little-endian | must be 36, else InvalidCorrelationInfo |
| 4–19 | correlationId | correlation_id |
| 20–35 | reserved | not read |
What may follow the request depends on its flag 0x08:
Flag 0x08 | After the request | Result |
|---|---|---|
| clear | nothing | accepted, correlation_id is None |
| clear | any byte | UnexpectedX224Data(n) |
| set | nothing | accepted, correlation_id is None |
| set | type 0x06, length 36, then 32 more bytes | accepted, correlation_id is Some(..) |
| set | from 4 bytes on, another type or another length | InvalidCorrelationInfo { structure_type, length } |
| set | type and length right, fewer than 36 bytes; or fewer than 4 bytes | Truncated { expected: 36, actual } |
| set | more than 36 bytes | UnexpectedX224Data(n), n counting the bytes after the 36 |
A flag without the structure is accepted, as it was in 11.6.0; tshark marks such a segment malformed. MS-RDPBCGR requires a correlationId whose first byte is neither 0x00 nor 0xF4 and which holds no 0x0D byte: the decoder does not check it, and neither does tshark. No capture of the corpus carries a correlation info; frame 6 of rdp-x509.pcap, given one by hand (tested):
#![allow(unused)] fn main() { #[test] fn a_correlation_info_after_the_negotiation_request() { // No capture of the corpus carries one. This Connection Request is the // 47-byte segment of frame 6 of rdp-x509.pcap, with the flag 0x08 set // and a correlation info appended (MS-RDPBCGR §2.2.1.1.2). let raw = hex::decode(RDP_COOKIE_REQUEST_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let frame_6 = flow.transport.as_ref().unwrap().payload.unwrap(); let correlation_id = [ 0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6, 0x07, 0x18, 0x29, 0x3a, 0x4b, 0x5c, 0x6d, 0x7e, 0x8f, 0x90, ]; let mut segment = frame_6.to_vec(); segment[40] = 0x08; // flags of the request: CORRELATION_INFO_PRESENT segment.extend_from_slice(&[0x06, 0x00, 36, 0x00]); // type 0x06, length 36 segment.extend_from_slice(&correlation_id); segment.extend_from_slice(&[0; 16]); // reserved segment[3] = 47 + 36; // TPKT length segment[4] = 42 + 36; // length indicator let packet = RdpPacket::try_from(segment.as_slice()).unwrap(); let payload = &packet.pdus[0].payload; assert_eq!(payload.cookie_user(), Some("JOHN-PC ")); // the cookie is kept let RdpPayload::ConnectionRequest { negotiation: Some(request), .. } = payload else { panic!("expected a negotiation request, got {payload:?}"); }; assert!(request.correlation_info_present()); assert_eq!(request.correlation_id, Some(correlation_id)); assert!(request.standard_security_only()); // The flag without the structure is accepted, without an id. let mut flag_only = frame_6.to_vec(); flag_only[40] = 0x08; let packet = RdpPacket::try_from(flag_only.as_slice()).unwrap(); let RdpPayload::ConnectionRequest { negotiation: Some(request), .. } = &packet.pdus[0].payload else { panic!("expected a negotiation request, got {:?}", packet.pdus[0].payload); }; assert!(request.correlation_info_present()); assert_eq!(request.correlation_id, None); // The structure without the flag: 36 bytes after the request. let mut no_flag = segment.clone(); no_flag[40] = 0x00; assert_eq!( RdpPacket::try_from(no_flag.as_slice()), Err(RdpParseError::UnexpectedX224Data(36)) ); // A correlation info that declares 32 bytes... let mut length_32 = segment.clone(); length_32[49] = 32; assert_eq!( RdpPacket::try_from(length_32.as_slice()), Err(RdpParseError::InvalidCorrelationInfo { structure_type: 0x06, length: 32 }) ); // ... and one that TCP cuts 13 bytes in. assert_eq!( RdpPacket::try_from(&segment[..60]), Err(RdpParseError::Truncated { expected: 36, actual: 13 }) ); // InvalidNegotiation is left to a request that does not declare 8 // bytes; a request cut before its eighth byte is Truncated. let mut length_12 = frame_6.to_vec(); length_12[41] = 12; assert_eq!( RdpPacket::try_from(length_12.as_slice()), Err(RdpParseError::InvalidNegotiation { structure_type: 0x01, length: 12 }) ); assert_eq!( RdpPacket::try_from(&frame_6[..44]), Err(RdpParseError::Truncated { expected: 8, actual: 5 }) ); } }
MCS PDUs
#![allow(unused)] fn main() { pub struct McsPdu<'a> { pub kind: McsPduType, /// The whole PDU, choice or tag included. pub raw: &'a [u8], /// Decoded for Send Data. pub send_data: Option<McsSendData<'a>>, } pub enum McsPduType { ConnectInitial, ConnectResponse, ErectDomainRequest, DisconnectProviderUltimatum, AttachUserRequest, AttachUserConfirm, ChannelJoinRequest, ChannelJoinConfirm, SendDataRequest, SendDataIndication, } pub struct McsSendData<'a> { /// User id, from 1001. pub initiator: u16, pub channel_id: u16, /// Priority (two high bits) and segmentation (next two bits). pub priority_and_segmentation: u8, /// Declared length of the data. pub declared_length: Option<u16>, /// The data present in this segment. pub data: &'a [u8], } }
A Data TPDU carries one MCS PDU. The two connect PDUs of T.125 are BER: Connect-Initial is recognized by its tag 7F 65 ([APPLICATION 101]), Connect-Response by 7F 66 ([APPLICATION 102]), each followed by a readable BER length, short form or long form on one to four bytes, else InvalidBerLength. Their content, which tshark dissects further as T.124, stays in raw. Every other PDU is a DomainMCSPDU in PER, whose choice is the six high bits of the first byte:
| Choice | McsPduType |
|---|---|
| 1 | ErectDomainRequest |
| 8 | DisconnectProviderUltimatum |
| 10 | AttachUserRequest |
| 11 | AttachUserConfirm |
| 14 | ChannelJoinRequest |
| 15 | ChannelJoinConfirm |
| 25 | SendDataRequest |
| 26 | SendDataIndication |
Any other choice is UnknownMcsPdu(choice). The two Send Data PDUs, which carry the RDP traffic itself, are decoded further. On frame 32 of rdp-proprietary-encryption.pcap, offsets in the MCS PDU:
| Bytes | Field | Frame 32 |
|---|---|---|
| 0 | the choice, shifted left by 2 | 0x64: 25, Send Data Request |
| 1–2 | initiator, big-endian, plus 1001 | 7, so 1008 |
| 3–4 | channel_id, big-endian | 1003 |
| 5 | priority_and_segmentation | 0x70 |
| 6 | PER length, declared_length: one byte below 0x80, or two bytes 10xxxxxx xxxxxxxx (14 bits) | 80 |
| 7… | data, from the end of the length to the end of the TPKT, or of the segment if TCP cut it | 80 bytes |
A fragmented length (first byte 11xxxxxx) leaves declared_length at None, and data then starts right after the priority byte. The data are not decoded: they are the RDP payload as it travels, encrypted or not.
Frame 32, then a TPKT cut by TCP and its continuation (tested):
#![allow(unused)] fn main() { #[test] fn mcs_send_data_and_a_tpkt_cut_by_tcp() { // rdp-proprietary-encryption.pcap, frame 32: a Send Data Request, // whole in its segment. let raw = hex::decode(RDP_SEND_DATA_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "RDP"); let segment = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = RdpPacket::try_from(segment).unwrap(); assert!(!packet.truncated); let pdu = &packet.pdus[0]; assert_eq!(pdu.tpkt_length, 94); assert_eq!(pdu.cotp.pdu_type, CotpPduType::Data); assert_eq!(pdu.cotp.end_of_tsdu, Some(true)); let RdpPayload::Mcs(mcs) = &pdu.payload else { panic!("expected an MCS PDU, got {:?}", pdu.payload); }; assert_eq!(mcs.kind, McsPduType::SendDataRequest); let send = mcs.send_data.expect("a Send Data is decoded"); assert_eq!(send.initiator, 1008); // 7 on the wire, plus 1001 assert_eq!(send.channel_id, 1003); assert_eq!(send.priority_and_segmentation, 0x70); assert_eq!(send.declared_length, Some(80)); assert_eq!(send.data.len(), 80); // Frame 43: the segment holds 1 260 bytes of a TPKT of 1 421. It is // decoded on what is there, and marked. let raw = hex::decode(RDP_CUT_TPKT_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "RDP"); let segment = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = RdpPacket::try_from(segment).unwrap(); assert_eq!((segment.len(), packet.pdus[0].tpkt_length), (1260, 1421)); assert!(packet.truncated); let RdpPayload::Mcs(mcs) = &packet.pdus[0].payload else { panic!("expected an MCS PDU, got {:?}", packet.pdus[0].payload); }; let send = mcs.send_data.expect("a Send Data is decoded"); assert_eq!(send.declared_length, Some(1406)); assert_eq!(send.data.len(), 1245); // what this segment carries // Frame 44 carries the other 161 bytes, without a header of its own: // its first byte happens to be 3, but a reserved byte of 0x29 is not // a TPKT. let raw = hex::decode(RDP_TPKT_CONTINUATION_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "Unknown"); assert_eq!( RdpPacket::try_from(flow.transport.as_ref().unwrap().payload.unwrap()), Err(RdpParseError::InvalidTpkt { version: 3, reserved: 0x29 }) ); } }
Validations
All of them are RdpParseError, in packet_parser::errors::application::rdp:
| Error | When |
|---|---|
Truncated { expected, actual } | fewer than 7 bytes left for a TPKT, a TPDU shorter than its fixed part (3 bytes, 7 for a CR or CC), a negotiation structure shorter than its 8 bytes, a correlation info shorter than its 36, an empty MCS PDU, a Send Data shorter than 6 bytes, an empty segment |
InvalidTpkt { version, reserved } | a TPKT version other than 3, or a non-zero reserved byte |
TpktTooShort(u16) | a TPKT length below 7: the 4 bytes of its header and a TPDU of 3 |
UnexpectedTpdu(u8) | a TPDU other than CR, CC and DT |
InvalidNegotiation { structure_type, length } | a negotiation structure whose length field is not 8; the only case, since 11.7.0 |
InvalidCorrelationInfo { structure_type, length } | after a request with the flag 0x08, a structure whose type is not 0x06 or whose length field is not 36 (added in 11.7.0) |
UnexpectedX224Data(usize) | user data of a CR or CC that is neither a token nor a negotiation structure; bytes after a request without the flag 0x08, after a response or a failure, or after a correlation info |
UnknownMcsPdu(u8) | a DomainMCSPDU choice other than the eight above |
InvalidBerLength | an unreadable BER length after a connect tag |
Cotp(CotpParseError) | declared, never returned by the decoder |
A failure only means no label. On port 3389 or a declared port, the segment goes on down the table and comes out "Unknown" unless another rule takes it, TLS after the negotiation. Nothing is reported in corrupted: a port is a hint, and the payload may belong to something else.
Oracle: 861 segments, without reassembly
tests/rdp_golden.rs runs the five captures of pcaps_exemple/protocols/rdp/, taken from Zeek's test corpus (BSD 3-clause), and compares every segment that has a payload with tshark 4.6.6 run without TCP reassembly (tcp.desegment_tcp_streams:FALSE, the view of a stateless parser). tools/rdp_oracle.sh freezes, in tests/data/rdp_tshark_oracle.tsv, the highest layer tshark sees, the TPKT length, the COTP type, the token, the negotiation and the MCS PDU type. Zeek warns that many traces of its corpus are generated; the SOURCE.md of the folder settles the question for these five on their bytes, and sets aside rdp-invalid-length.pcap, whose bytes are fabricated.
| Segments | tshark | The crate |
|---|---|---|
| 83 | rdp, t125 or t124 | "RDP", with the same TPKT length, COTP type, token, negotiation and MCS type: 7 Connection Requests, 6 of them with a cookie, 7 Connection Confirms and 69 MCS PDUs |
| 481 | tls, or x509ce for a certificate | "TLS" for the 449 that start with a whole record; "Unknown" for the other 32: 27 continuations of a record cut by TCP, and 5 segments of rdp-to-ssl.pcap that start an Application Data record longer than themselves, which the TLS probe refuses |
| 287 | data for 278 segments that do not start with a TPKT, the 16 continuations of cut TPKTs among them; nothing above tcp for 9 segments it flags as out of order | "Unknown" |
| 10 | retransmissions, not dissected | not compared; labelled by their bytes, 6 "RDP" and 4 "TLS" |
The 69 MCS PDUs are 3 Connect-Initial, 2 Connect-Response, 1 Erect Domain Request, 1 Attach User Request, 1 Attach User Confirm, 6 Channel Join Requests, 6 Channel Join Confirms, 27 Send Data Requests, 21 Send Data Indications and 1 Disconnect Provider Ultimatum. In the golden histogram of the whole corpus, "RDP" counts 89 frames: these 83, and six of the retransmissions, two in each of rdp-no-cookie-mstshash.pcap, rdp-unknown-keyboard.pcap and rdp-x509.pcap, which the stateless parser labels by their bytes; the four others, copies of TLS records in rdp-no-cookie-mstshash.pcap, come out "TLS". The fuzz target parse_rdp runs nightly on the decoder: no panic, and on success the TPKTs tile the segment, the last one possibly cut, and every borrowed slice points into the input.
| Capture | Frames | Content |
|---|---|---|
rdp-x509.pcap | 15 | cookie mstshash=JOHN-PC, standard RDP security, Connect-Initial and Connect-Response |
rdp-unknown-keyboard.pcap | 11 | the same hosts and opening, a Connect-Initial with an unknown keyboard layout |
rdp-no-cookie-mstshash.pcap | 20 | no cookie; TLS, CredSSP and CredSSP with Early User Authorization Result offered, the last one selected, then TLS |
rdp-to-ssl.pcap | 658 | cookie mstshash=AWAKECODI, CredSSP selected, then the whole session in TLS |
rdp-proprietary-encryption.pcap | 542 | standard RDP security after a refused TLS: the whole MCS session, TPKTs of 1 421 bytes cut across two segments |
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- RDP over UDP (MS-RDPEUDP) is another transport, which the crate does not decode; the
rdpeudp*captures of Zeek's corpus were left out. - No reassembly: a TPKT cut by TCP is decoded on its first segment when it starts that segment, and its continuation stays
"Unknown", like the continuations of TLS records. A segment that starts with a continuation is refused whole, the complete TPKTs that follow it included: frame 77 ofrdp-proprietary-encryption.pcapholds two. - Fast-path PDUs, which MS-RDPBCGR sends without the TPKT, X.224 and MCS headers, fail the TPKT check and stay
"Unknown"; tshark leaves them atdataas well. Of the 262datasegments of the corpus that do not continue a cut TPKT, 241 start with a byte whose two low bits are clear, the mark of a fast-path PDU, where a TPKT has 3. - The correlation info is not checked further: the decoder keeps its
correlationIdwithout checking the bytes MS-RDPBCGR forbids in it, and reads neither its flags nor its reserved bytes. A request flag0x08without the structure is accepted. - No connection state: after a TLS or CredSSP negotiation the label is
"TLS", and nothing records that those records belong to an RDP connection, nor which protocol it selected. - The connect PDUs are not opened: the T.124 conference data of a Connect-Initial or Connect-Response, where the keyboard layout of
rdp-unknown-keyboard.pcapsits, stays inraw. - The Send Data contents are raw: the RDP PDUs they carry are
data. - Flags and failure codes are numbers; the crate documents them but does not name them.
RTCP
RTCP, the RTP Control Protocol (RFC 3550 §6), travels beside an RTP stream: each end reports what it sent and what it received, names itself, and says goodbye. The decoder was added in 13.3.0 (#354, PR #362). The module is packet_parser::parse::application::protocols::rtcp, the errors are RtcpError, in packet_parser::errors::application::rtcp, and the label is "RTCP".
#![allow(unused)] fn main() { pub struct RtcpCompound<'a> { /* the datagram, validated */ } pub struct RtcpPacket<'a> { pub padding: bool, // the body ends with padding pub count: u8, // five bits: what they count depends on the type pub packet_type: RtcpPacketType, pub body: &'a [u8], // what follows the four-byte header } pub struct RtcpSenderInfo { pub ntp_timestamp: u64, // wallclock time of the report pub rtp_timestamp: u32, // the same instant on the clock of the stream pub packet_count: u32, pub octet_count: u32, } }
A datagram carries one RTCP packet or several, back to back: a compound packet (§6.1). RtcpCompound::try_from validates the whole datagram once; packets() then gives the packets in wire order without allocating, and as_bytes() the datagram. The types are #[non_exhaustive], and every body borrows from the datagram.
| Type | RtcpPacketType | count is | Defined in |
|---|---|---|---|
| 200 | SenderReport | the number of report blocks | RFC 3550 §6.4.1 |
| 201 | ReceiverReport | the number of report blocks | RFC 3550 §6.4.2 |
| 202 | SourceDescription | the number of chunks | RFC 3550 §6.5 |
| 203 | Goodbye | the number of sources | RFC 3550 §6.6 |
| 204 | ApplicationDefined | a subtype | RFC 3550 §6.7 |
| 205 | TransportFeedback | a feedback message type | RFC 4585 §6.2 |
| 206 | PayloadFeedback | a feedback message type | RFC 4585 §6.3 |
| 207 | ExtendedReport | reserved | RFC 3611 |
Two methods read what a consumer most often wants. sender_ssrc() is the SSRC that opens the body of every packet but a Source Description and a Goodbye, whose body is a list of sources. sender_info() is Some for a Sender Report: the NTP timestamp, the RTP timestamp and the two counters. The report blocks, the SDES items and the feedback messages stay bytes. Two constants are public: RTCP_VERSION and RTCP_HEADER_LENGTH, 4.
The last datagram a phone sends at the end of a call (tested):
#![allow(unused)] fn main() { #[test] fn a_compound_rtcp_datagram() { let raw = hex::decode(RTCP_SR_SDES_BYE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); // No port, no Decode As: the blind rule reads the content. assert_eq!(label(&flow), Some("RTCP")); let compound = RtcpCompound::try_from(payload(&flow)).unwrap(); let packets: Vec<_> = compound.packets().collect(); let types: Vec<_> = packets.iter().map(|packet| packet.packet_type).collect(); assert_eq!( types, [ RtcpPacketType::SenderReport, RtcpPacketType::SourceDescription, RtcpPacketType::Goodbye, ] ); // 28, 48 and 28 bytes: the three packets tile the 104 bytes. let lengths: Vec<_> = packets.iter().map(|packet| 4 + packet.body.len()).collect(); assert_eq!(lengths, [28, 48, 28]); assert_eq!(compound.as_bytes().len(), 104); // The Sender Report: no report block, the sender and its counters. let report = &packets[0]; assert_eq!(report.count, 0); assert_eq!(report.sender_ssrc(), Some(0x3796_cb71)); let info = report.sender_info().unwrap(); assert_eq!(info.ntp_timestamp >> 32, 1_120_470_986); assert_eq!(info.rtp_timestamp, 9411); assert_eq!((info.packet_count, info.octet_count), (9, 1548)); // SDES and BYE carry a list of sources, not a sender: one each. assert_eq!(packets[1].count, 1); assert_eq!(packets[1].sender_ssrc(), None); assert_eq!(packets[1].sender_info(), None); assert_eq!(packets[2].count, 1); // The bodies are borrowed, not decoded: the reason of the Goodbye // is still in its bytes. assert!(packets[2].body.ends_with(b"session shutdown\0\0\0")); } }
Detection: any UDP port
| Where | Rule | Probe | Accepts |
|---|---|---|---|
| any UDP port | blind rule 75 | ProbeId::RtcpBlind | a datagram RtcpCompound::try_from accepts, opened by a Sender Report or a Receiver Report, or made of one feedback packet alone |
a UDP port declared with ParseConfig::decode_as(port, DecodeAsProtocol::Rtcp) | tried before the table | ProbeId::Rtcp | any datagram RtcpCompound::try_from accepts |
RTCP has no port of its own: by convention it takes the port after the one of its RTP stream, and RFC 5761 lets both share one. Rule 75 is the last UDP rule of the table: every probe with a stronger signature has had the datagram first.
RTCP has what RTP lacks. Each packet says its length, and the lengths must tile the datagram to its last byte. The packet type is one of eight values. Each type has a minimum size, which grows with its count: a Sender Report with two report blocks is at least 76 bytes. On top of the decoder, the blind rule asks for the opening RFC 3550 §6.1 imposes, a Sender Report or a Receiver Report first. It accepts one exception, the reduced-size RTCP of RFC 5506: a single feedback packet, type 205 or 206, alone in its datagram.
DecodeAsProtocol::Rtcp, new in 13.3.0 and the last of the 34 variants, resolves to the label RTCP, the guard Udp and the probe Rtcp: on a declared port, any well-formed datagram is RTCP, whatever its first packet.
Validations
| Part | Check | Error |
|---|---|---|
| Packet | at least the four bytes of its header | RtcpError::TooShort { expected, actual } |
| Version | 2 | InvalidVersion |
| Packet type | 200 to 207 | UnknownPacketType |
| Length | the packet it announces fits in what remains of the datagram | TruncatedPacket { declared, available } |
| Padding, with the P bit | the last byte of the body is a multiple of four, not zero, and not longer than the body | InvalidPadding |
| Size | the body, without its padding, holds what the type and the count require | PacketTooShortForType { packet_type, count, expected, actual } |
| Padding | only on the last packet of the datagram | InvalidPadding |
The checks run in this order on each packet, from the first to the last, and the first failure is the error. Nothing may follow the last packet: a byte left over is a packet too short for its header.
| Type | Minimum body |
|---|---|
| Sender Report | 24 bytes, the SSRC and the sender information, plus 24 for each report block |
| Receiver Report | 4 bytes, the SSRC, plus 24 for each report block |
| Source Description | 8 bytes for each chunk |
| Goodbye | 4 bytes for each source |
| Application-defined | 8 bytes, the SSRC and a four-character name |
| Feedback, 205 and 206 | 8 bytes, the SSRC of the sender and the SSRC of the media source |
| Extended Report | 4 bytes, the SSRC |
Two refusals on the bytes of the corpus (tested):
#![allow(unused)] fn main() { #[test] fn what_rtcp_refuses() { let raw = hex::decode(RTCP_SR_SDES_BYE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let datagram = payload(&flow); // The lengths must tile the datagram: one byte less, and the // Goodbye runs past the end. assert_eq!( RtcpCompound::try_from(&datagram[..103]).unwrap_err(), RtcpError::TruncatedPacket { declared: 28, available: 27 } ); // An RTP packet of the same call: its second byte, 8, is no RTCP // packet type. let raw = hex::decode(RTP_PCMA_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!( RtcpCompound::try_from(payload(&flow)).unwrap_err(), RtcpError::UnknownPacketType(8) ); } }
What is not RTCP
Each row was checked against the crate, on a UDP port without a rule of its own, then on the same port declared Rtcp:
| Payload | Blind | Declared | Why |
|---|---|---|---|
| the Sender Report, SDES and BYE of the example | "RTCP" | "RTCP" | |
| its Sender Report alone, 28 bytes | "RTCP" | "RTCP" | a report may come alone |
| its SDES and BYE, without the report | "Unknown" | "RTCP" | well formed, but a compound packet opens with a report |
| its BYE alone | "Unknown" | "RTCP" | the same |
| one feedback packet of the LINE call | "RTCP" | "RTCP" | reduced-size RTCP |
| that feedback packet followed by a BYE | "Unknown" | "RTCP" | a feedback packet opens no compound packet |
| the example with one byte more | "Unknown" | "Unknown" | the lengths no longer tile the datagram |
| an RTP packet of the same call | "Unknown" | "Unknown" | its second byte, 8, is no packet type |
| the example, on TCP | "Unknown" | "Unknown" | the guard is UDP |
The seventh row is what makes the rule safe to run blind, and what RTP has no equivalent of. A datagram is RTCP only if its first byte is 0x80 to 0xBF, its second one of two values, or of two others when the packet is alone, and its length field, 16 bits, matches the size of the datagram or leads to another header that passes the same tests.
Oracle: 52 datagrams
The golden test tests/rtcp_golden.rs compares the crate with tshark 4.6.9. tools/rtcp_oracle.sh freezes, in tests/data/rtcp_tshark_oracle.tsv, one line per datagram that tshark dissects as RTCP: the types and the lengths of its packets, the SSRC of each sender, and the sender information of a Sender Report.
| Capture | RTCP | What |
|---|---|---|
sip/wireshark_aaa.pcap | 1 | the Sender Report, SDES and BYE of the example |
ntp/ndpi_line.pcap | 11 | feedback packets, each alone in its datagram |
rtcp/terrain_rtcp_censure.pcap | 40 | 20 Sender Reports and 20 Receiver Reports, each with one report block and followed by an SDES |
The third capture is new. The corpus had no Receiver Report, and no public capture with one was found, so 40 datagrams were taken from a field capture of the maintainer and censored by tools/censor_capture.py before they were published. Addresses, ports, NTP timestamps and the text of the SDES items were rewritten; packet types, lengths, counts and SSRC are the original ones. Its SOURCE.md lists each rewritten field.
The crate and tshark give RTCP the same 52 datagrams, and no other frame of the corpus gets the label. In the golden histogram "RTCP" went from 0 to 52.
What is left out
The limits every protocol shares are on the Limits page. The ones below are this protocol's own.
- The bodies. Report blocks, SDES items, the reason of a Goodbye and feedback messages are returned as bytes.
- SRTCP (RFC 3711) encrypts the packets and adds an index and an authentication tag after the last one. The lengths no longer tile the datagram, which stays
"Unknown", even on a declared port. - A compound packet that opens with another type than a report is named on a declared port only.
- RTCP multiplexed with RTP on one port (RFC 5761) is named packet by packet: the RTCP datagrams get their label, the RTP ones do not, unless the port is declared
Rtp. - RTCP over TCP is not read.
RTP
RTP, the Real-time Transport Protocol (RFC 3550), carries sound and video: each datagram is a slice of a stream, with a sequence number and a timestamp to put the slices back in order. The decoder was added in 13.3.0 (#353, PR #358). The module is packet_parser::parse::application::protocols::rtp, the errors are RtpError, in packet_parser::errors::application::rtp, and the label is "RTP".
RTP is the one protocol of the crate with a decoder, a label and no rule in the dispatch table: parse gives the label on a port the caller declares, and nowhere else. The reason is below.
#![allow(unused)] fn main() { pub struct RtpPacket<'a> { pub version: u8, // always 2 pub marker: bool, // the end of a video frame, the start of a talkspurt pub payload_type: u8, // seven bits pub sequence_number: u16, pub timestamp: u32, // in units of the payload clock pub ssrc: u32, // the synchronization source pub csrc: CsrcList<'a>, // zero to fifteen contributing sources pub extension: Option<RtpHeaderExtension<'a>>, pub payload: &'a [u8], // without the padding pub padding_length: u8, // count byte included; 0 without the P bit } pub struct RtpHeaderExtension<'a> { pub profile: u16, // 0xBEDE: the one-byte elements of RFC 8285 pub data: &'a [u8], // a multiple of four bytes } }
RtpPacket and RtpHeaderExtension are #[non_exhaustive], and everything borrows from the datagram. CsrcList is a view over the list a mixer fills: len(), is_empty(), iter() for the identifiers in wire order, as_bytes(). static_payload_name() names the static payload types of RFC 3551, PCMU for 0, PCMA for 8, MP2T for 33; it is None for a dynamic type, 96 to 127, whose meaning is in the signalling of the call. Two constants are public: RTP_VERSION and RTP_FIXED_HEADER_LENGTH, 12.
The header, the CSRC list, the extension, the payload and the padding tile the datagram: nothing is left over, and nothing is guessed. The payload itself, the sound or the picture, is not decoded.
Detection: a declared port, and nothing else
| Where | Rule | Probe | Accepts |
|---|---|---|---|
a UDP port declared with ParseConfig::decode_as(port, DecodeAsProtocol::Rtp) | tried before the table | ProbeId::Rtp | any packet RtpPacket::try_from accepts |
| any other port | none | none | nothing: the packet is "Unknown" |
A phone call says where its media goes: the SDP body of the SIP INVITE and of its answer name the UDP ports. A caller that reads them, or that knows the ports of its cameras, declares them. One packet of a G.711 call, before and after (tested):
#![allow(unused)] fn main() { #[test] fn rtp_is_named_on_a_declared_port() { let raw = hex::decode(RTP_PCMA_HEX).unwrap(); // No rule of the table names RTP: two fixed bits prove nothing. let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("Unknown")); // The decoder reads the packet all the same. let packet = RtpPacket::try_from(payload(&flow)).unwrap(); assert_eq!(packet.payload_type, 8); assert_eq!(packet.static_payload_name(), Some("PCMA")); assert!(!packet.marker); assert_eq!(packet.sequence_number, 28590); assert_eq!(packet.timestamp, 1240); assert_eq!(packet.ssrc, 0x3796_cb71); assert!(packet.csrc.is_empty()); assert_eq!(packet.extension, None); // 160 samples at 8 000 Hz: 20 ms of sound, no padding. assert_eq!(packet.payload.len(), 160); assert_eq!(packet.padding_length, 0); // The caller knows the media port, from the SDP of the call: once // declared, the same frame is RTP. let config = ParseConfig::new().decode_as(40392, DecodeAsProtocol::Rtp); let flow = parse_with(LinkType::ETHERNET, &raw, &config).unwrap(); assert_eq!(label(&flow), Some("RTP")); } }
DecodeAsProtocol::Rtp resolves to the label RTP, the guard Udp and the probe Rtp. The guard is UDP alone: RTP over TCP (RFC 4571) prefixes each packet with its length, which the crate does not read.
Why there is no blind rule
A blind rule stands on a signature, and RTP has none: no magic, no length field, no checksum. Of the 96 bits of its header, two are fixed, the version. Any datagram whose first byte is 0x80 to 0xBF and that is long enough has a well-formed RTP header, whatever it carries.
13.3.0 was developed with a blind rule, the last of the UDP cascade, with three more demands: no CSRC, a payload type outside 64 to 95, a payload that is not empty. It named the 15 011 RTP frames of the oracle. It also named eight frames that are not RTP:
| Frames | What they are |
|---|---|
3, in The-Ultimate-PCAP.pcapng | RDP over UDP, whose header starts with 0x80 |
3, in wireshark_8579_radardata.pcap | lines of text on UDP 7001 |
2, in ndpi_quic_interop_V.pcapng | QUIC Version Negotiation off port 443 |
Eight frames is few. But a label of the crate is a statement, and a consumer that builds a flow matrix cannot tell the eight from the others. No tightening of the probe brings the count to zero: the header has too few bits to stand on. The rule was removed before the release (#364, PR #365), and a test of the crate checks that no frame of those three captures is labelled RTP any more.
What proves RTP is a flow, not a packet: several datagrams between the same two ports, with one SSRC and sequence numbers that follow each other. That needs memory, and parse has none (Limits). A consumer that keeps a table of flows can confirm RTP that way, then declare the port, or keep the label itself. RtpPacket::try_from gives it the two fields to compare.
Validations
| Part | Check | Error |
|---|---|---|
| Datagram | at least the 12 bytes of the fixed header | RtpError::TooShort { expected, actual } |
| Version | 2 | InvalidVersion |
| Payload type | not 72 to 76 | RtcpPayloadType |
| CSRC list | CC identifiers of four bytes fit in the datagram | TruncatedCsrcList { count, expected, actual } |
| Extension, with the X bit | its four-byte header and the words it announces fit | TruncatedExtension { expected, actual } |
| Padding, with the P bit | the last byte counts at least one byte, and at most what follows the header | InvalidPadding { padding, available } |
The payload types 72 to 76 are reserved (RFC 3551 §6) because of RTCP: with the marker bit, they give a second byte of 200 to 204, the first five RTCP packet types. A Sender Report read as RTP would be a packet of type 72 with its marker set; the decoder refuses it, and the dispatch then names it for what it is, even on a port declared RTP (tested):
#![allow(unused)] fn main() { #[test] fn rtp_refuses_an_rtcp_datagram() { let raw = hex::decode(RTCP_SR_SDES_BYE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); // The second byte of a Sender Report is 200: read as RTP, a marker // bit and payload type 72, which RFC 3551 reserves for that reason. assert_eq!( RtpPacket::try_from(payload(&flow)).unwrap_err(), RtpError::RtcpPayloadType(72) ); // Even on a port declared RTP, the datagram is not RTP. The table // then names it by its content. let config = ParseConfig::new().decode_as(40393, DecodeAsProtocol::Rtp); let flow = parse_with(LinkType::ETHERNET, &raw, &config).unwrap(); assert_eq!(label(&flow), Some("RTCP")); } }
A payload may be empty: the twelve bytes of a header alone are a valid packet.
On a declared port
Each row was checked against the crate, on a port declared Rtp:
| Payload | Label | Why |
|---|---|---|
| a packet of the corpus, on UDP | "RTP" | |
| the same packet, on TCP | "Unknown" | the guard is UDP |
| the same packet, on a port that is not declared | "Unknown" | no rule of the table gives the label |
| its first twelve bytes | "RTP" | an empty payload is valid |
its first byte changed to 0x40, version 1 | "Unknown" | InvalidVersion |
| its CC field set to 1 | "RTP" | four bytes of the payload are read as a CSRC |
| its P bit set, the last byte being 213 | "Unknown" | InvalidPadding: 213 bytes do not fit |
| an RTCP Sender Report | "RTCP" | RtcpPayloadType, then the table |
A declared port is a statement of the caller: on it, everything that has the shape of RTP is RTP. The sixth row shows the cost. The decoder cannot know that a packet has no CSRC, only that the header says so.
Oracle: 15 011 frames
The golden test tests/rtp_golden.rs compares the crate with tshark 4.6.9, whose rtp_udp heuristic is switched on and whose T.38 dissector is switched off. tools/rtp_oracle.sh freezes, in tests/data/rtp_tshark_oracle.tsv, one line per frame that tshark dissects as RTP: the payload type, the marker, the sequence number, the timestamp, the SSRC, the number of CSRC, the length of the extension and the padding. No capture was added: the four were already in the corpus.
| Capture | RTP frames | What |
|---|---|---|
The-Ultimate-PCAP.pcapng | 7 907 | SIP calls, video, and 457 SRTP packets |
wireshark_FAX-Call-t38-CA-TDM-SIP-FB-1.pcap | 6 995 | G.711 before and after a fax |
ndpi_line.pcap | 100 | a LINE call, with header extensions and padding |
wireshark_aaa.pcap | 9 | G.711 A-law, the call of the SIP page |
The test checks three things:
- without Decode As, no frame of these captures is labelled
"RTP"; - with the destination port of each frame of the oracle declared, the 15 011 are labelled
"RTP"; - for each one,
RtpPacket::try_fromgives the fields of tshark, and the five parts tile the datagram.
SRTP (RFC 3711) encrypts the payload and leaves the header in clear, so its 457 packets decode like the others. tshark gives T.38 the G.711 packets that follow the fax re-INVITE of the second capture, because it follows the call; the oracle switches that dissector off, and the crate reads them as RTP.
What is left out
The limits every protocol shares are on the Limits page. The ones below are this protocol's own.
- No label without a declared port. A consumer that does not know the media ports sees
"Unknown", and has to confirm the flow itself. - Nothing ties a packet to its session. The SSRC, the sequence number and the timestamp are read, not followed: a gap, a reordering or a change of source is the consumer's to see.
- The payload. No codec is decoded, and a dynamic payload type has no name.
- The header extension is returned as bytes: the elements of RFC 8285 are not split.
- SRTP decodes as RTP: the header does not say that the payload is encrypted.
- RTP over TCP (RFC 4571) and RTP interleaved in RTSP are not read.
RTPS
Real-Time Publish-Subscribe, the wire protocol of DDS (OMG DDSI-RTPS 2.x), added in 11.6.0 (#120) with the defense lot (#125). DDS is the middleware of recent combat system architectures (NGVA, GVA, naval systems) and of ROS 2, and RTPS succeeds GIOP/MIOP in that role. The module is packet_parser::parse::application::protocols::rtps. Since 13.0.0 its submodule dds also reads the DDS layer of a DATA: inline QoS, serialized data and discovery (#317, below).
Detection: a magic, then an exact tiling
An RTPS message fills one UDP datagram. As for PTP on UDP, the pipeline gives the datagram a label, "RTPS", and nothing more: the decode is RtpsPacket::try_from on the transport payload.
The rule is a blind probe, rule(ApplicationProtocol::Rtps, Guard::Udp, ProbeId::Rtps), in the blind cascade of the dispatch table, right after the blind NTP rule and, since 11.8.0, before the blind Valmet DNA rule, then ASTERIX. There is no port guard: Cyclone DDS and Connext Micro send between random unicast ports, which is why the dispatch probes blind (frame 9 below goes from 54020 to 58584, the Connext Micro capture of the corpus to 21914). What identifies RTPS is its first four bytes, then its structure:
#![allow(unused)] fn main() { ProbeId::Rtps => { (payload.starts_with(b"RTPS") || payload.starts_with(b"RTPX")) && RtpsPacket::try_from(payload).is_ok() } }
- the magic is a constant-cost guard, as for GIOP: the decoder only runs on a datagram that starts with
RTPS, or withRTPX, a variant RTI Connext emits; - the decoder reads the whole payload, never a
PROBE_CAPprefix of 18 KiB, which since 11.7.0 only the probes of the four text protocols keep: a 60 KBDATA_FRAGis still RTPS, and the six ofwireshark_15227_reassembly_one_each.pcapng, up to 65 064 bytes of payload, are labelled; - the submessages must tile the datagram exactly; a reserved
submessageId, a body too short for its kind, or a HEADER_EXTENSION out of place or with a wrongmessageLengthrefuses the message.
A refused message is not a corruption: the label is not given, the datagram goes on down the table and usually comes out "Unknown", with nothing in corrupted. RTPS is probed on UDP only, and there is no DecodeAsProtocol variant for it: a rule without a port guard has no port to extend.
Cyclone DDS on the macOS loopback, between two random ports (tested):
#![allow(unused)] fn main() { #[test] fn rtps_is_recognized_by_its_magic_on_any_udp_port() { // Frame 9 of talker-listener-rtps.pcapng: Cyclone DDS on the macOS // loopback (LINKTYPE_NULL), between two random unicast ports. let raw = hex::decode(CYCLONE_FRAME_9_HEX).unwrap(); let flow = parse(LinkType::NULL, &raw).unwrap(); let transport = flow.transport.as_ref().unwrap(); assert_eq!( (transport.source_port, transport.destination_port), (Some(54020), Some(58584)) ); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "RTPS"); // The pipeline gives the label; the protocol parser decodes the payload. let payload = transport.payload.unwrap(); let RtpsPacket::Message(message) = RtpsPacket::try_from(payload).unwrap() else { panic!("expected a message, not a ping"); }; assert_eq!(&message.header.magic, b"RTPS"); assert_eq!((message.header.version_major, message.header.version_minor), (2, 1)); assert_eq!(message.header.vendor_id, 0x0110); // Eclipse Cyclone DDS // Four submessages tile the datagram after the 20-byte header, every // one of them little-endian (flag E). let kinds: Vec<SubmessageKind> = message.submessages.iter().map(|s| s.kind).collect(); assert_eq!( kinds, [ SubmessageKind::InfoDestination, SubmessageKind::InfoTimestamp, SubmessageKind::Data, SubmessageKind::Heartbeat, ] ); let bodies: Vec<usize> = message.submessages.iter().map(|s| s.body.len()).collect(); assert_eq!(bodies, [12, 8, 48, 28]); assert_eq!(20 + bodies.iter().map(|len| 4 + len).sum::<usize>(), payload.len()); assert!(message.submessages.iter().all(|s| s.little_endian)); let SubmessageDetails::InfoTimestamp { timestamp: Some(time) } = message.submessages[1].details else { panic!("expected an INFO_TS with a timestamp"); }; assert_eq!(time.seconds, 1_625_943_735); // 2021-07-10 19:02:15 UTC let SubmessageDetails::Data { reader_id, writer_id, writer_sequence_number, serialized_payload, .. } = message.submessages[2].details else { panic!("expected a DATA"); }; // The built-in participant message reader and writer, as tshark names them. assert_eq!((reader_id, writer_id), (0x0002_00c7, 0x0002_00c2)); assert_eq!(writer_sequence_number, 1); assert!(serialized_payload); assert!(matches!( message.submessages[3].details, SubmessageDetails::Heartbeat { first_sequence_number: 1, last_sequence_number: 1, count: 2, .. } )); } }
The message
#![allow(unused)] fn main() { pub enum RtpsPacket<'a> { Message(RtpsMessage<'a>), Ping(RtpsPing), } pub struct RtpsMessage<'a> { pub header: RtpsHeader, pub submessages: Vec<RtpsSubmessage<'a>>, // in wire order } pub struct RtpsHeader { pub magic: [u8; 4], // RTPS, or RTPX (RTI Connext) pub version_major: u8, pub version_minor: u8, pub vendor_id: u16, // 0x0101 RTI Connext, 0x0110 Cyclone DDS... pub guid_prefix: [u8; 12], } }
Every type of the module is #[non_exhaustive]. RtpsPacket::version() returns (major, minor), vendor_id() the vendor, and message() the message, None for a ping.
The header is the 20 bytes of DDSI-RTPS 2.5 §9.4.4:
| Bytes | Field | Note |
|---|---|---|
| 0–3 | magic | RTPS or RTPX; anything else is InvalidMagic |
| 4 | version_major | 2; anything else is UnsupportedVersion: RTPS 1.x, another format, is not decoded |
| 5 | version_minor | not checked: 1 in 230 frames of the corpus, 2 in the CoreDX one |
| 6–7 | vendor_id | big-endian |
| 8–19 | guid_prefix | the twelve bytes, as they are |
The RTI ping
RTI Connext also sends sixteen-byte "pings" to probe a participant: the magic, the version, the vendorId and the text NDDSPING, with neither guidPrefix nor submessage. They are outside the specification, but tshark counts them as RTPS, and so does the crate:
#![allow(unused)] fn main() { pub struct RtpsPing { pub magic: [u8; 4], pub version_major: u8, pub version_minor: u8, pub vendor_id: u16, pub text: [u8; 8], // NDDSPING } }
A payload of exactly 16 bytes ending with NDDSPING is an RtpsPacket::Ping, its magic and version still checked; sixteen bytes without the text are a truncated header, Truncated { expected: 20, actual: 16 }. The corpus has eight pings, seven in RTPS_Discovery.pcapng and one in rtps.pcap, all counted by the golden test; the one of rtps.pcap (tested):
#![allow(unused)] fn main() { #[test] fn the_rti_ping_is_rtps_without_submessages() { // Frame 1 of rtps.pcap: sixteen bytes, magic, version, vendorId, NDDSPING. let raw = hex::decode(RTI_PING_FRAME_1_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "RTPS"); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); assert_eq!(payload.len(), 16); let packet = RtpsPacket::try_from(payload).unwrap(); let RtpsPacket::Ping(ping) = &packet else { panic!("expected a ping"); }; assert_eq!(&ping.text, b"NDDSPING"); assert_eq!(packet.vendor_id(), 0x0101); // RTI Connext assert_eq!(packet.version(), (2, 1)); assert!(packet.message().is_none()); } }
Submessages
After the header, the message is a run of submessages, each introduced by four bytes (§9.4.5.1):
| Bytes | Field | Note |
|---|---|---|
| 0 | submessageId | gives kind; a reserved value is ReservedSubmessageId |
| 1 | flags | bit 0x01 is E, the byte order; the other bits depend on the kind |
| 2–3 | octetsToNextHeader | the length of the body, in the byte order of E |
#![allow(unused)] fn main() { pub struct RtpsSubmessage<'a> { pub kind: SubmessageKind, pub id: u8, pub flags: u8, pub little_endian: bool, // flag E pub octets_to_next_header: u16, // as carried by the wire pub body: &'a [u8], // after the four header bytes, zero-copy pub details: SubmessageDetails, } }
Byte order: one flag per submessage
little_endian is flag E, flags & 0x01. Each submessage chooses its own byte order, and the crate reads in it every number of the submessage: octetsToNextHeader, sequence numbers, counts, fragment numbers and sizes, numBits, timestamps. A SequenceNumber_t is a signed high half then an unsigned low half, each in that order, returned as an i64. Three fields do not follow E: the entity ids, kept as the four octets of the EntityId_t read big-endian (0x000003c2 for the built-in publications writer, for instance), the vendorId, big-endian in INFO_SRC as in the header, and the checksum of a HEADER_EXTENSION, big-endian too. All 544 submessages of the corpus set E: only the crate's unit tests, on synthetic bytes, read big-endian ones.
octetsToNextHeader: a length, or zero
The body is octetsToNextHeader bytes long. Zero means that the submessage runs to the end of the message, which only the last one can do, except for PAD and INFO_TS, where zero is an empty body. octets_to_next_header keeps what the wire carries, body what it covers; a length beyond the end of the datagram is SubmessageOverflow. The thirteen zeros of the corpus are the final DATA of the thirteen OpenDDS messages; the first of them (tested):
#![allow(unused)] fn main() { #[test] fn a_zero_octets_to_next_header_runs_to_the_end_of_the_message() { // Frame 1 of wireshark_6449_opendds_messenger.pcap: OpenDDS, an INFO_TS // then a DATA whose octetsToNextHeader is 0. let raw = hex::decode(OPENDDS_FRAME_1_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "RTPS"); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = RtpsPacket::try_from(payload).unwrap(); assert_eq!(packet.vendor_id(), 0x0103); // OpenDDS let message = packet.message().expect("a message, not a ping"); let data = &message.submessages[1]; assert_eq!(data.kind, SubmessageKind::Data); assert_eq!(data.flags, 0x0b); // K, Q and E assert_eq!(data.octets_to_next_header, 0); // as carried by the wire... assert_eq!(data.body.len(), payload.len() - 20 - (4 + 8) - 4); // ...to the end let SubmessageDetails::Data { writer_id, writer_sequence_number, inline_qos, serialized_payload, serialized_key, .. } = data.details else { panic!("expected a DATA"); }; assert_eq!(writer_id, 0x0000_0102); // high = -1, low = 0: `tshark -T fields` prints -4294967296 too. assert_eq!(writer_sequence_number, -4_294_967_296); assert!(inline_qos && serialized_key && !serialized_payload); } }
The sequence number of that DATA has a high half of −1, like those of frames 12 and 13, the two other DATA of the capture that carry a key and no data: −4 294 967 296 as an i64, which is also what tshark -T fields prints, where tshark -V shows the unsigned 18 446 744 069 414 584 320.
Kinds and their fields
SubmessageKind names the identifiers of DDSI-RTPS 2.5, of DDS Security 1.1 and of the vendor range; the HEADER_EXTENSION that RTPS 2.5 adds at 0x00 has been among them since 11.7.0 (#186), and has its own section. SubmessageDetails decodes, for the kinds of the specification, the entity ids, sequence numbers, counters, timestamps and fragmentation fields, once the body has been checked to be long enough for them:
submessageId | SubmessageKind | SubmessageDetails | Minimum body |
|---|---|---|---|
0x00 HEADER_EXTENSION | HeaderExtension | HeaderExtension(RtpsHeaderExtension) | the fields its flags announce, 0 to 40 |
0x15 DATA | Data | Data { reader_id, writer_id, writer_sequence_number, inline_qos, serialized_payload, serialized_key } | 20 |
0x16 DATA_FRAG | DataFrag | DataFrag { reader_id, writer_id, writer_sequence_number, fragment_starting_number, fragments_in_submessage, fragment_size, sample_size } | 32 |
0x07 HEARTBEAT | Heartbeat | Heartbeat { reader_id, writer_id, first_sequence_number, last_sequence_number, count } | 28 |
0x06 ACKNACK | AckNack | AckNack { reader_id, writer_id, bitmap_base, num_bits, count, final_flag } | 24 + bitmap |
0x08 GAP | Gap | Gap { reader_id, writer_id, gap_start, gap_list_base, num_bits } | 28 + bitmap |
0x13 HEARTBEAT_FRAG | HeartbeatFrag | HeartbeatFrag { reader_id, writer_id, writer_sequence_number, last_fragment_number, count } | 24 |
0x12 NACK_FRAG | NackFrag | NackFrag { reader_id, writer_id, writer_sequence_number, fragment_number_base, num_bits, count } | 28 + bitmap |
0x09 INFO_TS | InfoTimestamp | InfoTimestamp { timestamp: Option<RtpsTime> } | 8; nothing with flag I |
0x0e INFO_DST | InfoDestination | InfoDestination { guid_prefix } | 12 |
0x0c INFO_SRC | InfoSource | InfoSource { version_major, version_minor, vendor_id, guid_prefix } | 20 |
0x0d INFO_REPLY_IP4 | InfoReplyIp4 | Opaque | 8 |
0x0f INFO_REPLY | InfoReply | Opaque | 4 |
0x01 PAD | Pad | Opaque | — |
0x30–0x34 | SecureBody, SecurePrefix, SecurePostfix, SecureRtpsPrefix, SecureRtpsPostfix | Opaque | — |
0x80–0xff | VendorSpecific(id) | Opaque | — |
| any other | — | — | ReservedSubmessageId |
The bitmap of a SequenceNumberSet or a FragmentNumberSet is numBits rounded up to 32-bit words, 4 × ⌈numBits / 32⌉ bytes, and the count of an ACKNACK or a NACK_FRAG comes after it: the crate checks that the bitmap fits before reading the count. An RtpsTime is seconds: u32 and fraction: u32, in 2⁻³² s. Of the flags, details exposes Q, D and K of a DATA (inline_qos, serialized_payload, serialized_key), F of an ACKNACK (final_flag) and I of an INFO_TS (timestamp: None); the others stay in flags. What follows the fixed fields stays in body, as raw bytes. For a DATA and a DATA_FRAG, the DDS layer reads the inline QoS and the serialized data from there, on demand.
Nine kinds occur in the corpus, a list the golden test checks; over its 223 messages, INFO_TS appears 159 times, DATA 153, INFO_DST 96, HEARTBEAT 64, ACKNACK 61, DATA_FRAG 6, GAP 3, INFO_SRC once and the vendor submessage 0x80 of CoreDX once. HEADER_EXTENSION, HEARTBEAT_FRAG, NACK_FRAG, PAD, the two INFO_REPLY and the security submessages occur in no capture.
The header extension
RTPS 2.5 adds a submessage that extends the header (§8.3.3.2, §8.3.7 and §9.4.5.2): the length of the message, a send timestamp, two extension fields of 4 and 8 bytes, a checksum and parameters. In 11.6.0 the crate refused it as ReservedSubmessageId { id: 0, offset: 20 }, and the datagram came out "Unknown". Since 11.7.0 its fields are in SubmessageDetails::HeaderExtension:
#![allow(unused)] fn main() { pub struct RtpsHeaderExtension { pub message_length: Option<u32>, // L pub send_timestamp: Option<RtpsTime>, // T pub u_extension: Option<[u8; 4]>, // U pub w_extension: Option<[u8; 8]>, // W pub checksum: Option<RtpsChecksum>, // C1, C2 pub parameters: bool, // P } pub enum RtpsChecksum { Crc32c(u32), // C2 alone Crc64Xz(u64), // C1 alone Md5([u8; 16]), // C1 and C2 } }
Each field is present when its flag is set, in this order on the wire:
| Flag | Bit | Field | Bytes | Read as |
|---|---|---|---|---|
| E | 0x01 | — | — | the byte order of the submessage |
| L | 0x02 | message_length | 4 | u32, in the order of E |
| T | 0x04 | send_timestamp | 8 | RtpsTime, in the order of E |
| U | 0x08 | u_extension | 4 | raw bytes |
| W | 0x10 | w_extension | 8 | raw bytes |
| C2, C1 | 0x20, 0x40 | checksum | 4, 8 or 16 | big-endian whatever E (Table 9.8): CRC-32C, CRC-64/XZ or MD5 |
| P | 0x80 | parameters | the rest of the body | a ParameterList, raw: header_extension_parameters() |
A body shorter than the fields its flags announce is SubmessageTooShort. Bytes after them, without P, are accepted and stay in body. RtpsSubmessage::header_extension_parameters() returns the ParameterList of a HEADER_EXTENSION whose P flag is set, as raw bytes: its parameters, the final PID_SENTINEL included, are neither decoded nor checked. Any other submessage, or no P flag, gives None.
The checksum is not verified: the decoder reads it and keeps it, it does not compute a CRC or an MD5 over the message. Two other things are checked, which tshark 4.6.6 does not check:
- the position: a HEADER_EXTENSION comes right after the header, at offset 20, or not at all (§8.3.3.2, §8.3.7.3); anywhere else it is
MisplacedHeaderExtension { offset }; - the
messageLength, when L is set: one message per UDP datagram (§9.5), so it must equal the length of the datagram, elseHeaderExtensionLengthMismatch { declared, actual }.
No capture of the corpus carries a HEADER_EXTENSION (rtps.sm.id == 0x00: no frame), so the golden test and the histogram did not move. One, put by hand into frame 9 (tested):
#![allow(unused)] fn main() { #[test] fn a_header_extension_right_after_the_header() { // No capture of the corpus carries a HEADER_EXTENSION. This one is put // by hand between the header and the first submessage of frame 9, // little-endian like the rest of the message, with flags L and C2. let raw = hex::decode(CYCLONE_FRAME_9_HEX).unwrap(); let frame_9 = &raw[4 + 20 + 8..]; let mut payload = frame_9[..20].to_vec(); payload.extend_from_slice(&[0x00, 0x23, 8, 0]); // id, flags C2 | L | E, 8 bytes payload.extend_from_slice(&144u32.to_le_bytes()); // messageLength, in the order of E payload.extend_from_slice(&[0xde, 0xad, 0xbe, 0xef]); // a CRC-32C nobody computed payload.extend_from_slice(&frame_9[20..]); assert_eq!(payload.len(), 144); let packet = RtpsPacket::try_from(payload.as_slice()).unwrap(); let message = packet.message().expect("a message, not a ping"); assert_eq!(message.submessages.len(), 5); let extension = &message.submessages[0]; assert_eq!(extension.kind, SubmessageKind::HeaderExtension); let SubmessageDetails::HeaderExtension(fields) = extension.details else { panic!("expected a HEADER_EXTENSION, got {:?}", extension.details); }; assert_eq!(fields.message_length, Some(144)); // the length of the datagram // Read big-endian whatever E, and not verified: the message is accepted. assert_eq!(fields.checksum, Some(RtpsChecksum::Crc32c(0xdead_beef))); assert_eq!(fields.send_timestamp, None); // no flag T assert_eq!((fields.u_extension, fields.w_extension), (None, None)); assert!(!fields.parameters); assert_eq!(extension.header_extension_parameters(), None); assert_eq!(message.submessages[1].kind, SubmessageKind::InfoDestination); // Flag P alone: a ParameterList, here its PID_SENTINEL only, kept raw. let mut payload = frame_9[..20].to_vec(); payload.extend_from_slice(&[0x00, 0x81, 4, 0, 0x01, 0x00, 0x00, 0x00]); payload.extend_from_slice(&frame_9[20..]); let packet = RtpsPacket::try_from(payload.as_slice()).unwrap(); let extension = &packet.message().unwrap().submessages[0]; assert_eq!(extension.header_extension_parameters(), Some(&[0x01, 0x00, 0x00, 0x00][..])); // Every flag but P, on the INFO_DST of frame 9 turned HEADER_EXTENSION: // 4 + 8 + 4 + 8 + 16 bytes of fields, in a body of 12. let mut too_short = frame_9.to_vec(); too_short[20..22].copy_from_slice(&[0x00, 0x7f]); assert_eq!( RtpsPacket::try_from(too_short.as_slice()), Err(RtpsParseError::SubmessageTooShort { id: 0x00, offset: 20, expected: 40, actual: 12, }) ); } }
Validations
The decoder of the message returns nine variants of RtpsParseError, in packet_parser::errors::application::rtps. The five others, added in 13.0.0, come from the DDS layer and never refuse a message.
| Error | When |
|---|---|
Truncated { expected, actual } | fewer than the 20 bytes of the header, or fewer than the four bytes of a submessage header where one must start (expected counts from the start of the message) |
InvalidMagic([u8; 4]) | the first four bytes are neither RTPS nor RTPX |
UnsupportedVersion { major, minor } | the major version is not 2 |
NoSubmessage | a header and nothing after it |
ReservedSubmessageId { id, offset } | an identifier that is neither one of DDSI-RTPS 2.5, HEADER_EXTENSION included, nor 0x30–0x34 (DDS Security), nor 0x80–0xff |
SubmessageOverflow { id, offset, declared, available } | octetsToNextHeader beyond the end of the message |
SubmessageTooShort { id, offset, expected, actual } | a body shorter than its kind requires (entity ids, sequence numbers, bitmap, the fields of a HEADER_EXTENSION) |
MisplacedHeaderExtension { offset } | a HEADER_EXTENSION that is not the first submessage (added in 11.7.0) |
HeaderExtensionLengthMismatch { declared, actual } | a HEADER_EXTENSION whose messageLength is not the length of the datagram (added in 11.7.0) |
The refusal of an unknown identifier departs from the specification: rule 3 of DDSI-RTPS 2.5 §8.3.4.1 asks a receiver to ignore a submessage whose submessageId it does not know and to go on with the next one. The crate refuses the message instead, because the closed table of identifiers is part of the signature its blind probe relies on.
The probe only asks whether the decode succeeds, so any of them means "not RTPS". Each one on the bytes of frame 9, one modification at a time (tested):
#![allow(unused)] fn main() { #[test] fn a_message_that_does_not_tile_its_datagram_is_refused() { // The 132-byte payload of frame 9 of talker-listener-rtps.pcapng, then // one modification at a time. let raw = hex::decode(CYCLONE_FRAME_9_HEX).unwrap(); let payload = &raw[4 + 20 + 8..]; // after LINKTYPE_NULL, IPv4 and UDP assert_eq!(payload.len(), 132); assert_eq!(RtpsPacket::try_from(&payload[..20]), Err(RtpsParseError::NoSubmessage)); let mut other_magic = payload.to_vec(); other_magic[..4].copy_from_slice(b"GIOP"); assert_eq!( RtpsPacket::try_from(other_magic.as_slice()), Err(RtpsParseError::InvalidMagic(*b"GIOP")) ); let mut version_1 = payload.to_vec(); version_1[4] = 1; // RTPS 1.x, another format assert_eq!( RtpsPacket::try_from(version_1.as_slice()), Err(RtpsParseError::UnsupportedVersion { major: 1, minor: 1 }) ); let mut reserved = payload.to_vec(); reserved[20] = 0x02; // the first submessageId assert_eq!( RtpsPacket::try_from(reserved.as_slice()), Err(RtpsParseError::ReservedSubmessageId { id: 0x02, offset: 20 }) ); // 0x00 is the HEADER_EXTENSION of RTPS 2.5: the first submessage or none. let mut misplaced = payload.to_vec(); misplaced[36] = 0x00; // the INFO_TS at offset 36 assert_eq!( RtpsPacket::try_from(misplaced.as_slice()), Err(RtpsParseError::MisplacedHeaderExtension { offset: 36 }) ); let mut wrong_length = payload.to_vec(); wrong_length[20..22].copy_from_slice(&[0x00, 0x03]); // first, with flags L and E wrong_length[24..28].copy_from_slice(&131u32.to_le_bytes()); // its messageLength assert_eq!( RtpsPacket::try_from(wrong_length.as_slice()), Err(RtpsParseError::HeaderExtensionLengthMismatch { declared: 131, actual: 132 }) ); let mut overflow = payload.to_vec(); overflow[22] = 200; // INFO_DST declares 200 bytes instead of 12 assert_eq!( RtpsPacket::try_from(overflow.as_slice()), Err(RtpsParseError::SubmessageOverflow { id: 0x0e, offset: 20, declared: 200, available: 108, }) ); let mut short = payload[..124].to_vec(); short[102] = 20; // the HEARTBEAT at offset 100 keeps 20 of its 28 bytes assert_eq!( RtpsPacket::try_from(short.as_slice()), Err(RtpsParseError::SubmessageTooShort { id: 0x07, offset: 100, expected: 28, actual: 20, }) ); let mut longer = payload.to_vec(); longer.push(0); // one byte cannot hold a submessage header assert_eq!( RtpsPacket::try_from(longer.as_slice()), Err(RtpsParseError::Truncated { expected: 136, actual: 133 }) ); // In the frame, a refused message is not RTPS, and not a corruption // either: the datagram goes on to the next rules. let mut frame = raw.clone(); frame[4 + 20 + 8 + 22] = 200; let flow = parse(LinkType::NULL, &frame).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "Unknown"); assert!(flow.corrupted.is_none()); } }
The DDS layer
RTPS carries DDS. A DATA holds a sample of a topic, sometimes with inline QoS. The DATA of the discovery writers say what a participant announces of itself and of its endpoints. Since 13.0.0 the module rtps::dds reads them (#317).
Detection does not change. The probe and RtpsPacket::try_from stop at the submessages, as above. The DDS layer is decoded on demand, from an RtpsSubmessage, by three methods:
| Method | Gives | None for |
|---|---|---|
inline_qos() | the ParameterList of a DATA or a DATA_FRAG with flag Q | any other submessage; no flag Q |
serialized_payload() | the encapsulation header and the data of a DATA with flag D or K, or of a DATA_FRAG that starts at fragment 1 | any other submessage; a DATA with neither D nor K; a later fragment |
discovery() | the built-in topic and the ParameterList of a DATA from an SPDP or SEDP writer | another writer; a DATA_FRAG; a DATA with neither data nor key |
Each one returns Option<Result<_, RtpsParseError>>. None means that the submessage carries nothing of the kind. Err means that what it carries is malformed: the message stays RTPS, and its frame keeps its label. Every slice they return borrows from body. The types of rtps::dds are #[non_exhaustive], like the others.
Where the data starts
A DATA, like a DATA_FRAG, starts with extraFlags and octetsToInlineQos, two bytes each, before its entity ids and its sequence number. octetsToInlineQos counts from the byte after it. The crate checks that it points between the end of the fixed fields and the end of the body:
| Submessage | Fixed fields | octetsToInlineQos accepted |
|---|---|---|
| DATA | 20 bytes | 16 to body.len() − 4 |
| DATA_FRAG | 32 bytes | 28 to body.len() − 4 |
Any other value is InvalidOctetsToInlineQos. With flag Q, the inline QoS start there, and the data follow their PID_SENTINEL. Without it, the data start there. Frame 3 above carries 16: its data start right after the 20 fixed bytes. SubmessageDetails exposes neither extraFlags nor octetsToInlineQos.
Inline QoS
inline_qos() reads the ParameterList of flag Q, an RtpsParameterList like the data of discovery. Its headers and values are in the byte order of the submessage, flag E. tshark finds inline QoS in 17 frames of the corpus, with two PIDs only:
| PID | Accessor | Frames |
|---|---|---|
0x0070 PID_KEY_HASH | key_hash() | 14 |
0x0071 PID_STATUS_INFO | status_info() | 4 |
The example of the refusals starts with one of them: an RTI Connext participant that leaves.
The serialized payload
serialized_payload() decodes the four-byte encapsulation header, then keeps what follows:
#![allow(unused)] fn main() { pub struct RtpsSerializedPayload<'a> { pub encapsulation: RtpsEncapsulation, // the representation identifier, bytes 0-1 pub options: u16, // the representation options, bytes 2-3 pub data: &'a [u8], // the rest } }
- The header is big-endian, whatever flag E.
optionsis kept as carried.dataruns to the end of the submessage, padding included. For a DATA_FRAG, it stops at the end of the first fragment.RtpsSerializedPayload::parsedoes the same on any bytes.
RtpsEncapsulation names the representation identifiers of DDS-XTypes 1.3 (Table 60):
| Identifier | RtpsEncapsulation | name() | Data |
|---|---|---|---|
0x0000, 0x0001 | CdrBe, CdrLe | CDR_BE, CDR_LE | classic CDR |
0x0002, 0x0003 | PlCdrBe, PlCdrLe | PL_CDR_BE, PL_CDR_LE | a ParameterList, which parameters() decodes |
0x0004 | Xml | XML | XML |
0x0010, 0x0011 | Cdr2Be, Cdr2Le | CDR2_BE, CDR2_LE | XCDR2 |
0x0012, 0x0013 | PlCdr2Be, PlCdr2Le | PL_CDR2_BE, PL_CDR2_LE | XCDR2 of a mutable type: EMHEADERs, not a ParameterList |
0x0014, 0x0015 | DCdr2Be, DCdr2Le | D_CDR2_BE, D_CDR2_LE | XCDR2 of an appendable type: a DHEADER first |
| any other | Other(code) | None | unknown |
code() gives the identifier back. little_endian() gives the byte order of the data: Some(false) for the Be forms, Some(true) for the Le ones, None for XML and Other. is_parameter_list() is true for the two PL_CDR only, and parameters() is None for any other encapsulation.
The DDS oracle of the corpus holds 155 encapsulation headers:
| Encapsulation | Headers |
|---|---|
PL_CDR_LE (0x0003) | 101, the discovery announcements |
CDR_LE (0x0001) | 54 |
| any other | 0 |
Discovery: SPDP and SEDP
discovery() recognizes the writer of a DATA by its entity id (DDSI-RTPS 2.5 §9.3.1.4, and DDS Security 1.1 for the secure writers):
| Writer entity id | RtpsBuiltinTopic | name() |
|---|---|---|
0x000100c2; secure 0xff0101c2 | Participant (SPDP) | DCPSParticipant |
0x000002c2 | Topic (SEDP) | DCPSTopic |
0x000003c2; secure 0xff0003c2 | Publication (SEDP) | DCPSPublication |
0x000004c2; secure 0xff0004c2 | Subscription (SEDP) | DCPSSubscription |
Any other writer gives None, the participant message writer 0x000200c2 of frame 9 among them. RtpsBuiltinTopic::from_writer is the same table, on its own.
#![allow(unused)] fn main() { pub struct RtpsDiscovery<'a> { pub topic: RtpsBuiltinTopic, pub secure: bool, // a DDS Security writer, 0xff...... pub key_only: bool, // flag K without flag D pub encapsulation: RtpsEncapsulation, // PL_CDR, big- or little-endian pub parameters: RtpsParameterList<'a>, } }
- The data must be PL_CDR. Any other encapsulation is
NotAParameterList. - The list is read in the byte order of the encapsulation, not of the submessage.
key_onlymarks a key alone: a participant or an endpoint that leaves.
The ParameterList
Inline QoS and discovery data are both an RtpsParameterList (§9.4.2.11):
#![allow(unused)] fn main() { pub struct RtpsParameterList<'a> { pub bytes: &'a [u8], // the parameters, without the PID_SENTINEL pub little_endian: bool, } pub struct RtpsParameter<'a> { pub id: u16, pub value: &'a [u8], // the length the header announces pub little_endian: bool, // the order of the list } }
The list is checked once, when it is decoded:
- every parameter fits in the list, its header and the value its length announces;
- a PID_SENTINEL ends it;
- the length of the sentinel is ignored, and so is what follows it.
RtpsParameterList::parse does the same on any bytes, and also returns the bytes it consumed, sentinel included. iter() gives the parameters in wire order, without the sentinel. get(id) gives the first one with that id. Two bits of its id are flags (§9.6.2.2.1), and name() names it:
| Method | Bit | Meaning |
|---|---|---|
is_vendor_specific() | 15, 0x8000 | a PID of the implementation that the vendorId names |
must_understand() | 14, 0x4000 | a receiver that does not understand it must ignore the whole submessage |
name() | — | its name in the specification, PID_TOPIC_NAME for instance, one of the 64 it knows; None for a vendor PID or an unknown one |
The crate reports the must-understand bit. It does not act on it.
A parameter reads its own value with string(), u32_value(), guid(), duration() and locator(). The list has fifteen typed accessors. Each one reads the first parameter of its PID, and gives None when it is absent or its value too short:
| Accessor | PID | Returns |
|---|---|---|
topic_name() | 0x0005 PID_TOPIC_NAME | &[u8], a CDR string without its NUL |
type_name() | 0x0007 PID_TYPE_NAME | &[u8] |
entity_name() | 0x0062 PID_ENTITY_NAME | &[u8] |
participant_guid() | 0x0050 PID_PARTICIPANT_GUID | [u8; 16]: guidPrefix, then entity id |
endpoint_guid() | 0x005a PID_ENDPOINT_GUID | [u8; 16] |
key_hash() | 0x0070 PID_KEY_HASH | [u8; 16], the GUID itself for a built-in topic |
status_info() | 0x0071 PID_STATUS_INFO | RtpsStatusInfo, read big-endian: disposed(), unregistered(), filtered() |
domain_id() | 0x000f PID_DOMAIN_ID | u32 |
protocol_version() | 0x0015 PID_PROTOCOL_VERSION | (u8, u8) |
vendor_id() | 0x0016 PID_VENDORID | u16, read big-endian, like the header's |
builtin_endpoint_set() | 0x0058 PID_BUILTIN_ENDPOINT_SET | u32, one bit per built-in endpoint |
participant_lease_duration() | 0x0002 PID_PARTICIPANT_LEASE_DURATION | RtpsDuration |
reliability() | 0x001a PID_RELIABILITY | RtpsReliability { kind, max_blocking_time } |
durability() | 0x001d PID_DURABILITY | RtpsDurabilityKind |
locators() | the six locator PIDs below | an iterator of (RtpsLocatorRole, RtpsLocator), in wire order |
Strings are bytes: nothing checks that they are UTF-8. The other value types:
RtpsDurationisseconds: i32andfraction: u32, in 2⁻³² s.is_infinite()tests DURATION_INFINITE:0x7fffffffseconds and a fraction of0xffffffff.RtpsLocatoriskind: i32,port: u32andaddress: [u8; 16].ipv4()reads the last four bytes of a kind 1 locator,ipv6()the sixteen of a kind 2 one. Other kinds keep their bytes.RtpsReliabilityKindkeeps the values of the wire:BestEffortis 1,Reliable2.max_blocking_timeisNonefor a four-byte value.RtpsDurabilityKindisVolatile,TransientLocal,TransientorPersistent, 0 to 3.- Both kinds have an
Other(u32)for any other value.
The PID of a locator gives its role:
| PID | RtpsLocatorRole | Reaches |
|---|---|---|
0x002f, 0x0030 | Unicast, Multicast | the data of an endpoint |
0x0031, 0x0048 | DefaultUnicast, DefaultMulticast | the data of the participant's endpoints, by default |
0x0032, 0x0033 | MetatrafficUnicast, MetatrafficMulticast | the metatraffic of the participant: discovery, heartbeats, acknowledgements |
Frame 3 of talker-listener-rtps.pcapng is the SPDP announcement of the participant of frame 9, to 239.255.0.1:7400. It names no entity. Two of its eleven parameters, 0x8007 and 0x8019, belong to Cyclone DDS (tested):
#![allow(unused)] fn main() { #[test] fn a_participant_announces_itself_through_spdp() { // Frame 3 of talker-listener-rtps.pcapng: the participant of frame 9 // announces itself to the SPDP multicast group, an INFO_TS then a DATA. let raw = hex::decode(CYCLONE_FRAME_3_HEX).unwrap(); let flow = parse(LinkType::NULL, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "RTPS"); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = RtpsPacket::try_from(payload).unwrap(); let message = packet.message().expect("a message, not a ping"); let data = &message.submessages[1]; assert_eq!(data.kind, SubmessageKind::Data); // Decoded on demand, from the submessage: the writer 0x000100c2 is SPDP's. assert!(data.inline_qos().is_none()); // no flag Q let discovery = data.discovery().expect("an SPDP writer").unwrap(); assert_eq!(discovery.topic, RtpsBuiltinTopic::Participant); assert_eq!(discovery.topic.name(), "DCPSParticipant"); assert_eq!(discovery.encapsulation, RtpsEncapsulation::PlCdrLe); assert!(!discovery.secure && !discovery.key_only); let list = discovery.parameters; let guid = list.participant_guid().unwrap(); assert_eq!(guid[..12], message.header.guid_prefix); // the sender itself assert_eq!(guid[12..], [0x00, 0x00, 0x01, 0xc1]); // ENTITYID_PARTICIPANT assert_eq!(list.vendor_id(), Some(0x0110)); // Cyclone DDS assert_eq!(list.protocol_version(), Some((2, 1))); assert_eq!(list.domain_id(), Some(0)); assert_eq!(list.builtin_endpoint_set(), Some(0x0000_0c3f)); let lease = list.participant_lease_duration().unwrap(); assert_eq!((lease.seconds, lease.fraction), (10, 0)); assert_eq!(list.entity_name(), None); // Cyclone DDS sends none // Where to reach the participant: its data, and its metatraffic. let locators: Vec<(RtpsLocatorRole, Option<Ipv4Addr>, u32)> = list .locators() .map(|(role, locator)| (role, locator.ipv4(), locator.port)) .collect(); let host = Some(Ipv4Addr::new(10, 0, 0, 46)); assert_eq!( locators, [ (RtpsLocatorRole::DefaultUnicast, host, 61_329), (RtpsLocatorRole::MetatrafficUnicast, host, 61_329), ] ); // Every parameter in wire order, the PID_SENTINEL left out. let ids: Vec<u16> = list.iter().map(|parameter| parameter.id).collect(); assert_eq!( ids, [0x002c, 0x0015, 0x0016, 0x0002, 0x0050, 0x0058, 0x000f, 0x0031, 0x0032, 0x8007, 0x8019] ); // Bit 15: two PIDs of Cyclone DDS, which the specification does not name. let vendor: Vec<u16> = list .iter() .filter(|parameter| parameter.is_vendor_specific()) .map(|parameter| parameter.id) .collect(); assert_eq!(vendor, [0x8007, 0x8019]); assert!(list.iter().all(|parameter| !parameter.must_understand())); assert_eq!(list.get(0x8007).unwrap().name(), None); // A PID without an accessor: its value, borrowed. ROS 2 writes its // enclave in PID_USER_DATA, a sequence of 10 octets. let user_data = list.get(0x002c).unwrap(); assert_eq!(user_data.name(), Some("PID_USER_DATA")); assert_eq!(user_data.u32_value(), Some(10)); assert_eq!(&user_data.value[4..14], b"enclave=/;"); } }
A publication, then its first sample
Frame 57 of the same capture is SEDP. The participant announces a writer of the topic rt/chatter, the one of the ROS 2 talker. Its endpoint GUID ends with the entity id 0x00001503. Frame 70 is a DATA of that writer, its first sample. A user writer is not a discovery one: discovery() is None (tested):
#![allow(unused)] fn main() { #[test] fn a_publication_announced_by_sedp_then_its_first_sample() { /// The UDP payload of a LINKTYPE_NULL frame the pipeline labels RTPS. fn datagram(raw: &[u8]) -> &[u8] { let flow = parse(LinkType::NULL, raw).unwrap(); assert_eq!(flow.application.unwrap().protocol.label(), "RTPS"); flow.transport.unwrap().payload.unwrap() } // Frame 57 of talker-listener-rtps.pcapng: the SEDP publications // writer, 0x000003c2, announces a writer of the participant. let raw = hex::decode(CYCLONE_FRAME_57_HEX).unwrap(); let packet = RtpsPacket::try_from(datagram(&raw)).unwrap(); let message = packet.message().unwrap(); let discovery = message.submessages[1].discovery().expect("an SEDP writer").unwrap(); assert_eq!(discovery.topic, RtpsBuiltinTopic::Publication); let list = discovery.parameters; assert_eq!(list.topic_name(), Some(&b"rt/chatter"[..])); assert_eq!(list.type_name(), Some(&b"std_msgs::msg::dds_::String_"[..])); let writer = list.endpoint_guid().unwrap(); assert_eq!(writer[..12], message.header.guid_prefix); assert_eq!(writer[12..], [0x00, 0x00, 0x15, 0x03]); // a user writer, no key let reliability = list.reliability().unwrap(); assert_eq!(reliability.kind, RtpsReliabilityKind::Reliable); assert!(reliability.max_blocking_time.unwrap().is_infinite()); assert_eq!(list.durability(), None); // no PID_DURABILITY in the list // Frame 70: a DATA of that writer. A user writer: no discovery, and // a payload that is not a ParameterList. let raw = hex::decode(CYCLONE_FRAME_70_HEX).unwrap(); let packet = RtpsPacket::try_from(datagram(&raw)).unwrap(); let data = &packet.message().unwrap().submessages[1]; let SubmessageDetails::Data { writer_id, .. } = data.details else { panic!("expected a DATA"); }; assert_eq!(writer_id.to_be_bytes(), writer[12..]); assert_eq!(data.discovery(), None); let payload = data.serialized_payload().expect("flag D").unwrap(); assert_eq!(payload.encapsulation, RtpsEncapsulation::CdrLe); assert_eq!(payload.encapsulation.name(), Some("CDR_LE")); assert_eq!(payload.encapsulation.little_endian(), Some(true)); assert_eq!(payload.options, 0); assert_eq!(payload.parameters(), None); // PL_CDR only // The crate stops at the bytes. The IDL of std_msgs/String reads // them as a CDR string: a u32 length, NUL included, then the text. assert_eq!(payload.data.len(), 20); // to the end of the submessage let length = u32::from_le_bytes(payload.data[..4].try_into().unwrap()) as usize; assert_eq!(&payload.data[4..4 + length], b"Hello World: 1\0"); } }
User data stays bytes
The crate stops at the encapsulation header of a user type. Its data is &[u8]: without the IDL of the type, nothing says how to read it. The example above reads its std_msgs/String by hand, a CDR string, Hello World: 1. The key of a user instance, flag K, stays bytes too. So do the XCDR2 and XML forms, which are named and not decoded.
Refusals of the DDS layer
Five variants were added at the end of RtpsParseError in 13.0.0. Only the DDS layer returns them, never RtpsPacket::try_from:
| Error | When | Returned by |
|---|---|---|
InvalidOctetsToInlineQos { octets_to_inline_qos, body } | octetsToInlineQos points into the fixed fields, or beyond the body | the three methods |
ParameterTruncated { offset, expected, actual } | a parameter header, or the value its length announces, overflows the list; offset counts from the start of the list | the three methods, RtpsParameterList::parse |
ParameterListUnterminated { length } | a list without PID_SENTINEL | the three methods, RtpsParameterList::parse |
SerializedPayloadTooShort { actual } | serialized data shorter than the four bytes of the encapsulation header | serialized_payload(), discovery(), RtpsSerializedPayload::parse |
NotAParameterList { encapsulation } | the data of a discovery writer are not PL_CDR | discovery() |
serialized_payload() and discovery() return the errors of a list too: they read the inline QoS to find where the data start. A refusal here refuses nothing else. The message still decodes, the probe still says RTPS, and the frame is not corrupted.
Frame 29 of rtps.pcap first, an RTI Connext participant that leaves: a DATA of the SPDP writer with inline QoS only. Then each refusal on its bytes, and NotAParameterList on those of frame 70 (tested):
#![allow(unused)] fn main() { #[test] fn inline_qos_and_the_refusals_of_the_dds_layer() { /// The DATA of a message, which must still decode as RTPS. fn data_of(message: &[u8]) -> RtpsSubmessage<'_> { let packet = RtpsPacket::try_from(message).expect("still an RTPS message"); packet.message().unwrap().submessages[1] } // Frame 29 of rtps.pcap: an RTI Connext participant leaves. Its SPDP // writer sends a DATA with flags Q and E, neither data nor key: the // inline QoS alone say which instance, and what happened to it. let raw = hex::decode(RTI_FRAME_29_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "RTPS"); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let data = data_of(payload); assert_eq!(data.flags, 0x03); let qos = data.inline_qos().expect("flag Q").unwrap(); assert!(qos.little_endian); // the byte order of the submessage let key = qos.key_hash().unwrap(); // the GUID of the participant assert_eq!(key[..12], payload[8..20]); // the guidPrefix of the header let status = qos.status_info().unwrap(); assert_eq!(status.flags, 0x03); assert!(status.disposed() && status.unregistered() && !status.filtered()); assert_eq!(data.serialized_payload(), None); // neither D nor K assert_eq!(data.discovery(), None); // The 88-byte message: the DATA at offset 32, its octetsToInlineQos // at 38, the inline QoS from 56 to the end, their PID_SENTINEL at 84. assert_eq!(payload.len(), 88); let mut pointer = payload.to_vec(); pointer[38] = 64; // beyond the 52 bytes of the body assert_eq!( data_of(&pointer).inline_qos(), Some(Err(RtpsParseError::InvalidOctetsToInlineQos { octets_to_inline_qos: 64, body: 52, })) ); let mut unterminated = payload.to_vec(); unterminated[84] = 0x00; // PID_SENTINEL turned PID_PAD, its length 1 kept assert_eq!( data_of(&unterminated).inline_qos(), Some(Err(RtpsParseError::ParameterTruncated { offset: 28, expected: 1, actual: 0 })) ); unterminated[86] = 0x00; // length 0: the list fits, and nothing ends it assert_eq!( data_of(&unterminated).inline_qos(), Some(Err(RtpsParseError::ParameterListUnterminated { length: 32 })) ); let mut no_data = payload.to_vec(); no_data[33] = 0x07; // flag D, and nothing after the inline QoS assert_eq!( data_of(&no_data).serialized_payload(), Some(Err(RtpsParseError::SerializedPayloadTooShort { actual: 0 })) ); assert_eq!( data_of(&no_data).discovery(), Some(Err(RtpsParseError::SerializedPayloadTooShort { actual: 0 })) ); // Frame 70 of talker-listener-rtps.pcapng, its writer id at 44 turned // into SPDP's: a CDR_LE payload is no discovery. let frame_70 = hex::decode(CYCLONE_FRAME_70_HEX).unwrap(); let mut not_a_list = frame_70[4 + 20 + 8..].to_vec(); not_a_list[44..48].copy_from_slice(&[0x00, 0x01, 0x00, 0xc2]); assert_eq!( data_of(¬_a_list).discovery(), Some(Err(RtpsParseError::NotAParameterList { encapsulation: 0x0001 })) ); // None of them refuses the message: the frame is still RTPS, and // nothing is corrupted. let mut frame = raw.clone(); frame[14 + 20 + 8 + 38] = 64; let flow = parse(LinkType::ETHERNET, &frame).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "RTPS"); assert!(flow.corrupted.is_none()); } }
Oracle: 231 frames, six implementations
The golden test tests/rtps_golden.rs runs the eight captures of pcaps_exemple/protocols/rtps/ and compares every frame with tshark 4.6.6 without IP reassembly, frozen by tools/rtps_oracle.sh in tests/data/rtps_tshark_oracle.tsv: version, vendorId, guidPrefix, the sequence of submessages with their octetsToNextHeader, the entity ids and the sequence numbers. Every frame of the oracle must come out "RTPS" and decode identically, every other frame of the folder must not: 231 frames, the 8 pings and the 4 RTPX messages among them. The other 16 frames of the folder are IPv4 fragments of RTPS_Discovery.pcapng, which tshark reassembles and a stateless parser never sees whole. In the golden histogram of pcaps_exemple/protocols/ (tests/golden_pcaps.rs), "RTPS" went from 0 to 231 and "Unknown" from 9 409 to 9 178: no frame of another folder comes out RTPS. The fuzz target parse_rtps runs nightly on the same decoder, and since 13.0.0 on its DDS layer too.
| Capture | RTPS frames | Implementation (vendorId) | Origin |
|---|---|---|---|
talker-listener-rtps.pcapng | 87 | Eclipse Cyclone DDS (0x0110), ROS 2 talker and listener, LINKTYPE_NULL | foxglove/rtps |
RTPS_Discovery.pcapng | 93 | RTI Connext (0x0101), discovery, pings, the RTPX messages | Wireshark wiki |
rtps.pcap | 29 | RTI Connext (0x0101) | nDPI test corpus |
wireshark_15227_reassembly_one_each.pcapng | 6 | RTI Connext (0x0101), DATA_FRAG datagrams of 55 to 65 KB | Wireshark issue 15227 |
wireshark_15868_micro_2_4_11.pcapng | 1 | RTI Connext Micro (0x010a), port 21914 | Wireshark issue 15868 |
wireshark_6449_opendds_messenger.pcap | 13 | OpenDDS (0x0103) | Wireshark issue 6449 |
wireshark_9378_ddsi.pcapng | 1 | OpenSplice (0x0102) | Wireshark issue 9378 |
wireshark_17630_default_multicast_locator.pcapng | 1 | CoreDX (0x0106), RTPS 2.2, a vendor submessage | Wireshark issue 17630 |
Two oracle details: tshark lists the identifier of a vendor submessage but not its octetsToNextHeader, so the comparison skips that length; and it prints a sequence number signed with -T fields, which is the form the oracle keeps.
The DDS layer: 137 frames, 101 announcements
The golden test tests/rtps_dds_golden.rs replays the same eight captures against a second oracle: tshark 4.6.9, frozen by tools/rtps_dds_oracle.sh in tests/data/rtps_dds_tshark_oracle.tsv. It holds a row for each frame that carries a parameter or an encapsulation header: 137 frames. Each row lists, in wire order:
- the encapsulation identifiers;
- the PIDs, PID_SENTINEL included;
- the topic, type and entity names;
- the participant and endpoint GUIDs, and the key hashes;
- the kind, port and IPv4 address of the locators;
- the status info, the reliability, the durability and the built-in endpoint set.
The crate rebuilds the same row from inline_qos(), serialized_payload() and discovery(). Every RTPS message of the folder must match its row, or have none.
| Capture | Frames in the DDS oracle |
|---|---|
talker-listener-rtps.pcapng | 57 |
RTPS_Discovery.pcapng | 33 |
rtps.pcap | 28 |
wireshark_6449_opendds_messenger.pcap | 13 |
wireshark_15227_reassembly_one_each.pcapng | 3, the DATA_FRAG of fragment 1 |
wireshark_15868_micro_2_4_11.pcapng | 1 |
wireshark_9378_ddsi.pcapng | 1 |
wireshark_17630_default_multicast_locator.pcapng | 1 |
| total | 137 |
Three oracle details:
- no IP reassembly, as for the first oracle;
rtps.enable_topic_infois off: otherwise tshark adds to user data the topic and type it remembers from discovery, which are not on the wire;- no domain column: the
rtps.domain_idof tshark comes from the port, not from PID_DOMAIN_ID.
A second test checks what tshark does not, on the 101 SPDP and SEDP announcements of five implementations:
| Check | Result |
|---|---|
| built-in topics | 61 DCPSParticipant, 19 DCPSPublication, 21 DCPSSubscription; no DCPSTopic, no secure writer, no key alone |
| PID_VENDORID of the 61 SPDP | RTI Connext 46, Cyclone DDS 11, OpenSplice 2, CoreDX 1, Connext Micro 1 |
| participant GUID | the guidPrefix of the sender, then ENTITYID_PARTICIPANT, 0x000001c1 |
| endpoint GUID | the guidPrefix of the sender, with a topic and a type name: 29 distinct topics |
| lease duration | in all 61 SPDP |
| PID_DOMAIN_ID | from Cyclone DDS only, 11 times, domain 0 |
| key hash of a built-in instance disposed or unregistered | the GUID of the sender, in frame 29 of rtps.pcap |
The sender is the guidPrefix of the header, or that of the last INFO_SRC. The OpenDDS capture carries no discovery.
The fuzz target parse_rtps calls the three methods on every submessage it decodes. When they succeed, every list, value and data slice points into the body of the submessage. The parameters tile their list, and every typed accessor reads without a panic. Three real frames seed its mutations, besides frames 8 and 9 of Cyclone DDS: the SPDP DATA of Connext Micro, frame 29 of rtps.pcap and frame 12 of the OpenDDS capture.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- User data: the data of a user type stays bytes after its encapsulation header, and so does its key. XCDR2, its mutable and appendable forms, and XML are named, not decoded. The
extraFlagsandoctetsToInlineQosof a DATA are not exposed. - The ParameterList: fifteen PIDs have a typed accessor; the others give their value as bytes, through
getanditer. The must-understand bit is reported, not acted on. - Discovery is read from a DATA only, not from an announcement cut into DATA_FRAG.
- Names: entity ids and GUID prefixes are numbers and bytes; tshark calls
0x000200c2ENTITYID_P2P_BUILTIN_PARTICIPANT_MESSAGE_WRITER, the crate does not. Only the discovery writers get a name, that of their built-in topic. - DDS Security: the secure submessages are recognized by their identifier, their bodies stay opaque.
discovery()recognizes the secure discovery writers; no capture has one. - The HEADER_EXTENSION checksum is read, not verified, and its ParameterList stays raw and unchecked.
- Unknown submessages refuse the message, where rule 3 of §8.3.4.1 asks to skip them.
- Reassembly:
DATA_FRAGfragments are not put back together, nor are the IPv4 fragments of a datagram.serialized_payload()of a DATA_FRAG gives the start of the data, from fragment 1 only. One message at a time, as everywhere in the crate. - RTPS 1.x is
UnsupportedVersion, and RTPS is only looked for on UDP.
SIP
SIP, the Session Initiation Protocol (RFC 3261), sets calls up, changes them and ends them: a phone registers with its server, invites another one, hangs up. The voice travels apart, in RTP; SIP carries the signalling only, as text, in a syntax borrowed from HTTP. The decoder was added in 13.2.0 (#342, PR #343). The module is packet_parser::parse::application::protocols::sip, the errors are SipError, in packet_parser::errors::application::sip, and the label is "SIP".
#![allow(unused)] fn main() { pub struct SipMessage<'a> { pub start_line: SipStartLine<'a>, pub headers: SipHeaders<'a>, // every header line, in wire order pub via: &'a str, // the first Via, raw pub from: &'a str, // raw: display name, URI, tag pub to: &'a str, pub call_id: &'a str, pub cseq: SipCseq<'a>, pub content_length: Option<u32>, // None when the header is absent pub body: &'a [u8], // cut at Content-Length } pub enum SipStartLine<'a> { Request { method: &'a str, uri: &'a str }, Response { status_code: u16, reason: &'a str }, } pub struct SipCseq<'a> { pub sequence: u32, // below 2^31 pub method: &'a str, // for a response, the method of the request it answers } }
The three types and both variants are #[non_exhaustive], and everything borrows from the payload. is_request() tells the two start lines apart, status_code() is None for a request, and method() gives the method of a request, or for a response the method its CSeq names. The five fields from via to cseq are the mandatory headers, found whatever their form on the wire, Call-ID or i. When a header occurs twice, the field holds the first one: for Via, the last hop the message crossed.
SipHeaders is the view over the whole header block, validated once while parsing, in the manner of HttpHeaders. iter() gives the (name, value) pairs in wire order, the names as written; len() and is_empty() count them. get(name) returns the first value of a name compared case-insensitively, and it knows the compact forms both ways: get("Call-ID") finds an i: line and get("i") a Call-ID: line. None of them allocates. Three constants are public: SIP_VERSION, SIP_METHODS and SIP_COMPACT_FORMS.
Detection: any port, UDP and TCP
| Where | Rule | Probe | Accepts |
|---|---|---|---|
| any TCP or UDP port | blind rule 63 | ProbeId::Sip | a head that SipMessage::try_from accepts, within the first PROBE_CAP bytes |
a port declared with ParseConfig::decode_as(port, DecodeAsProtocol::Sip) | tried before the table | ProbeId::Sip | the same |
Rule 63 sits in the blind cascade of the table, after the first SSH rule and just before HTTP. It has no transport guard: RFC 3261 §18 runs SIP over UDP and TCP alike. It has no port either. 5060 is the registered port, but a server may listen anywhere, and the content proves more than a port would. 5061 carries SIP inside TLS, which is labelled TLS: the crate does not decrypt.
A rule without a port and without a transport can only stand on a strong signature, and SIP has one:
- the version
SIP/2.0, compared case-insensitively (§7.1); - for a request, one of the 14 methods of the IANA registry, in upper case: methods are case-sensitive (§7.1);
- the five headers every request and every response carries (§8.1.1): Via, From, To, Call-ID and CSeq;
- a CSeq whose number is below 231 and whose method, for a request, is the method of the request line.
Before any of that, may_start_sip looks at the first bytes alone: a status line, or one of the 14 methods followed by a space. Almost every other payload stops there, at a constant cost. The two rules on either side cannot take a SIP message: the HTTP probe wants the version HTTP/, and SSDP, on UDP 1900, speaks HTTP too (NOTIFY * HTTP/1.1).
DecodeAsProtocol::Sip, new in 13.2.0, resolves to the label SIP, the guard Any and the probe of rule 63. A declared port is tried before the table, so it wins over a port rule that would accept the payload first. Like every declared port, it does not lift a terminal port such as mDNS on UDP 5353.
A server's 100 Trying to a REGISTER, with its headers in the order that server sends them (tested):
#![allow(unused)] fn main() { #[test] fn a_response_and_its_headers() { let raw = hex::decode(TRYING_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("SIP")); let message = SipMessage::try_from(payload(&flow)).unwrap(); let SipStartLine::Response { status_code, reason, .. } = message.start_line else { panic!("expected a status line, got {:?}", message.start_line); }; assert_eq!((status_code, reason), (100, "Trying")); assert!(!message.is_request()); assert_eq!(message.status_code(), Some(100)); // A response answers the request its CSeq names: here a REGISTER. assert_eq!(message.cseq.sequence, 6); assert_eq!(message.cseq.method, "REGISTER"); assert_eq!(message.method(), "REGISTER"); // The headers keep the order of the wire: this server puts Call-ID // first, Via fifth. let names: Vec<&str> = message.headers.iter().map(|(name, _)| name).collect(); assert_eq!(names, ["Call-ID", "CSeq", "From", "To", "Via", "Content-Length"]); assert!(message.via.starts_with("SIP/2.0/UDP 192.168.1.2;received=")); // `get` ignores case, and finds a long name by its compact form. assert_eq!(message.headers.get("i"), Some(message.call_id)); assert_eq!(message.headers.get("CSEQ"), Some("6 REGISTER")); assert_eq!(message.headers.get("Contact"), None); // Content-Length: 0, so the body is empty. assert_eq!(message.content_length, Some(0)); assert!(message.body.is_empty()); } }
The start line
| Start line | Example | SipStartLine | Checked |
|---|---|---|---|
Method SP Request-URI SP SIP-Version | REGISTER sip:sip.cybercity.dk SIP/2.0 | Request { method, uri } | the method is one of the 14; the URI is a scheme, a colon, then visible ASCII without a space; the version is SIP/2.0 |
SIP-Version SP Status-Code SP Reason-Phrase | SIP/2.0 100 Trying | Response { status_code, reason } | three digits, from 100 to 699; the reason may be empty |
The scheme follows absoluteURI in RFC 2396: a letter, then letters, digits, +, - or .. So sip:, sips:, tel: and urn: all pass. The 14 methods are those of the IANA registry of SIP methods:
| Method | Defined in |
|---|---|
INVITE, ACK, BYE, CANCEL, OPTIONS, REGISTER | RFC 3261 |
PRACK | RFC 3262 |
SUBSCRIBE, NOTIFY | RFC 6665 |
PUBLISH | RFC 3903 |
INFO | RFC 6086 |
REFER | RFC 3515 |
MESSAGE | RFC 3428 |
UPDATE | RFC 3311 |
Header lines
Each line of the head is a name, a colon and a value (§7.3.1). The name is a token (§25.1): letters, digits and ten marks, - . ! % * _ + ' ~ and the backquote, possibly followed by blanks before the colon. The blanks around the value are trimmed. A line that starts with a space or a tab continues the previous one: RFC 3261 still allows this folding, which HTTP gave up. The value is then returned raw, the CR LF and the blanks of the fold included.
A header may come in its long form or in a compact form of one letter (§7.3.3). SIP_COMPACT_FORMS holds the 20 pairs of the IANA registry, and the decoder accepts both forms of the five mandatory headers:
| Compact | Long | Compact | Long |
|---|---|---|---|
a | Accept-Contact | m | Contact |
b | Referred-By | n | Identity-Info |
c | Content-Type | o | Event |
d | Request-Disposition | r | Refer-To |
e | Content-Encoding | s | Subject |
f | From | t | To |
i | Call-ID | u | Allow-Events |
j | Reject-Contact | v | Via |
k | Supported | x | Session-Expires |
l | Content-Length | y | Identity |
The values are not decoded further. From, To and Via keep their display names, URIs and parameters as one string, and the body, SDP most of the time, is bytes.
The body is what follows the empty line, cut at Content-Length when the header is present. Over UDP, a datagram carries one whole message (§18.3), and every frame of the corpus has a body of exactly the announced length. Over TCP, the cut keeps a second message of the same segment out of the body of the first one; that second message is not decoded.
Validations
| Part | Check | Error |
|---|---|---|
| Head | ends with an empty line, CR LF CR LF | SipError::MissingHeaderTerminator |
| Head | valid UTF-8 | InvalidUtf8 |
| Request line | a method among the 14 | UnknownMethod |
| Request-URI | a scheme, a colon, visible ASCII | InvalidRequestUri |
| Version | SIP/2.0, in any case | InvalidVersion |
| Status code | three digits, from 100 to 699 | InvalidStatusCode |
| Header line | a token, a colon, a value, or the continuation of a fold | InvalidHeader |
| Mandatory headers | Via, From, To, Call-ID and CSeq, long or compact | MissingHeader, with the long name |
| CSeq | a number below 231, blanks, one of the 14 methods, nothing after | InvalidCseq |
| CSeq of a request | the method of the request line | CseqMethodMismatch { request, cseq } |
| Content-Length | decimal digits | InvalidContentLength |
The checks run in this order, and the first failure is the error. A status line is recognized by its version, so SIP/3.0 200 OK is read as a request line, and fails with UnknownMethod.
What is not SIP
The rule has no port and no transport, so the head is all that keeps other payloads out. Each row was checked against the crate, on UDP and on TCP, on port 5060 and on port 12345:
| Payload | Label | Why |
|---|---|---|
invite sip:… SIP/2.0, the five headers | "Unknown" | methods are case-sensitive |
INVITE sip:… sip/2.0, the five headers | "SIP" | the version is not |
FOO sip:… SIP/2.0, a method outside the registry | "Unknown" | UnknownMethod |
INVITE bob@biloxi.com SIP/2.0 | "Unknown" | the URI has no scheme |
INVITE sip:… SIP/3.0 | "Unknown" | InvalidVersion |
SIP/2.0 700 … | "Unknown" | the code goes up to 699 |
| an INVITE without CSeq | "Unknown" | MissingHeader("CSeq") |
an INVITE with CSeq: 1 ACK | "Unknown" | CseqMethodMismatch |
| a CSeq of 2 147 483 648 | "Unknown" | the number must be below 231 |
| a head without its empty line, or with LF line ends | "Unknown" | MissingHeaderTerminator |
OPTIONS / HTTP/1.1 | "HTTP" on TCP, "Unknown" on UDP | the version is HTTP's |
NOTIFY * HTTP/1.1 | "SSDP" on UDP 1900, "Unknown" elsewhere | the version is HTTP's |
OPTIONS rtsp://… RTSP/1.0 | "Unknown" | the version is RTSP's |
a keep-alive: CR LF CR LF, spaces, hello | "Unknown" | no start line |
Unlike the HTTP probe, the SIP probe does not accept line ends that are LF alone: RFC 3261 §7 asks for CR LF, and every message of the corpus has them.
Phones and servers keep their NAT bindings open with small datagrams on the SIP port. RFC 5626 uses CR LF pairs, or STUN; others send what they like. The two captures of the corpus that carry them (tested):
#![allow(unused)] fn main() { #[test] fn keepalives_are_not_sip() { // Frame 193 of aaa.pcap: five spaces on UDP 5060. let raw = hex::decode(SPACES_KEEPALIVE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(payload(&flow), b" "); assert_eq!( SipMessage::try_from(payload(&flow)).unwrap_err(), SipError::MissingHeaderTerminator ); assert_eq!(label(&flow), Some("Unknown")); // Frame 1 of sip_hello.pcapng: `hello`. The padding after the // datagram is not part of the payload. let raw = hex::decode(HELLO_KEEPALIVE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(payload(&flow), b"hello"); assert_eq!(label(&flow), Some("Unknown")); } }
Oracle: 201 frames
The golden test tests/sip_golden.rs compares the crate with tshark 4.6.9, without IP defragmentation or TCP reassembly, the view of a stateless parser. tools/sip_oracle.sh freezes, in tests/data/sip_tshark_oracle.tsv, one line per frame that tshark dissects as SIP. Each line holds the method or the status code, the number and the method of the CSeq, and the Content-Length. It keeps no Call-ID and no phone number. The captures are in pcaps_exemple/protocols/sip/, each with its provenance and its licence in SOURCE.md, and in the Ultimate PCAP:
| Capture | Frames | SIP | What |
|---|---|---|---|
wireshark_aaa.pcap | 691 | 81 | a soft phone behind a home router in 2005: REGISTER, 401 and 407, INVITE, CANCEL, 100, 183, 200, 403, 408, 480; around them, DNS, NetBIOS, DHCP, FTP and RTP |
wireshark_FAX-Call-t38-CA-TDM-SIP-FB-1.pcap | 7 217 | 92 | a fax call through a media gateway in 2008: INVITE, OPTIONS, BYE, 100, 180, 200, 488; around them, MEGACO, RTP and T.38 |
ndpi_sip_hello.pcapng | 30 | 8 | REGISTER, 401 and 200 with a Huawei SoftX3000 in 2022, and 22 hello keep-alives |
ndpi_http_on_sip_port.pcap | 4 | 0 | the negative: an HTTP GET and its 403, on TCP 5060 |
The-Ultimate-PCAP.pcapng | 51 328 | 20 | three calls in 2019: INVITE, 100, 180, 200, ACK, BYE |
The first two come from the Wireshark wiki, under the GPL; the two others from the test corpus of nDPI, under the LGPL 3.0. The test checks four things:
- the crate labels
"SIP"exactly the 201 frames of the oracle, and no other frame of these captures; - for each one,
SipMessage::try_fromgives the start line, the CSeq and the Content-Length of tshark; - the body has exactly the announced length;
- the first Via names UDP, as every message of the corpus travels over UDP.
The HTTP of the negative stays HTTP. tshark dissects one more frame as SIP: frame 15114 of the Ultimate PCAP, the first IPv4 fragment of a 2 017-byte INVITE. The crate does not reassemble IP (#105) and gives a fragment no application layer, so the oracle leaves it out, and a third test checks that it stays without one.
In the golden histogram "SIP" went from 0 to 181. Most of the other frames of these captures came in as "Unknown": the RTP, T.38 and MEGACO of the fax call, the keep-alives, the NetBIOS datagrams.
What is left out
The limits every protocol shares, reassembly among them, are on the Limits page. The ones below are this protocol's own.
- SIP over TCP. The corpus has no real TCP capture: the TCP path is covered by the crate's unit tests, on synthetic messages.
- A message over several segments. A head cut between two TCP segments is
"Unknown", because its empty line is in the next one. So are the segments that carry the rest of a message, and a head longer thanPROBE_CAP, 18 KiB. - IPv4 fragments. An INVITE whose SDP pushes the datagram beyond the MTU is fragmented, and no fragment is read.
- Keep-alives. CR LF pairs, STUN, spaces and
helloon port 5060 stay"Unknown". - SIP inside TLS is labelled TLS, and SIP over WebSocket (RFC 7118) is not decoded.
- Extension methods outside the IANA registry are not recognized.
- The values. No URI, Via parameter or SDP body is decoded, and a folded value is returned with its fold.
STANAG 5066 SIS
STANAG 5066 SIS, the Subnetwork Interface Sublayer of annex A (Edition 4, draft v1.6 published by Isode), added in 11.6.0 (#122) as part of the defense lot (#125): the layer that connects applications to an HF radio node, for links beyond the horizon, over TCP 5066. It carries notably ACP 142 (P_MUL) and the military messaging of STANAG 4406 annex E. The module is packet_parser::parse::application::protocols::stanag5066.
The unit is the S_PDU: the preamble 90 EB, a version byte, two bytes of primitive size and the type of the primitive, one of 27, each decoded into typed values. The decoder is stateless, like GIOP: it decodes the first S_PDU of a TCP segment, accepts one that overflows the segment, and says where the next one starts.
Detection: TCP 5066 only
#![allow(unused)] fn main() { // among the port rules, after IKE, ESP and NAT-keepalive: TCP 5066 on either side port_rule(ApplicationProtocol::Stanag5066, Guard::Tcp, is_stanag5066_tcp_port, ProbeId::Stanag5066), }
with the probe
#![allow(unused)] fn main() { ProbeId::Stanag5066 => SisPdu::try_from(payload).is_ok(), }
TCP 5066 is the IANA port (stanag-5066) and the one Wireshark registers. There is no blind rule: the preamble 90 EB 00, a type and a size are three fixed bytes and two constraints, too little to probe every TCP segment with. A node on another port is declared with ParseConfig::decode_as(port, DecodeAsProtocol::Stanag5066), which maps to the same probe behind the same TCP guard, (ApplicationProtocol::Stanag5066, Guard::Tcp, ProbeId::Stanag5066), evaluated before the table like every Decode As port. classify_payload called with no port (None, None) never answers STANAG 5066. Since 11.7.0 the probe judges the whole payload, as every probe does except the four text protocols (#185). Until 11.6.0 it saw only the first 18 KiB (PROBE_CAP), and a first S_PDU that ran past that bound was judged as a truncated one.
The guard on a real S_PDU moved to port 5067 (tested):
#![allow(unused)] fn main() { #[test] fn off_tcp_5066_an_s_pdu_needs_decode_as() { let mut raw = hex::decode(SIS_ACP142_REQUEST_HEX).unwrap(); // Rewrite the TCP destination port, after 14 bytes of Ethernet and 20 // of IPv4, from 5066 to 5067; `parse` does not verify the checksum. raw[36..38].copy_from_slice(&5067u16.to_be_bytes()); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let transport = flow.transport.as_ref().unwrap(); assert_eq!( (transport.source_port, transport.destination_port), (Some(41778), Some(5067)) ); // Still an S_PDU, but off port 5066 no rule runs the SIS probe, and // no other probe accepts it. assert!(SisPdu::try_from(transport.payload.unwrap()).is_ok()); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "Unknown"); let config = ParseConfig::new().decode_as(5067, DecodeAsProtocol::Stanag5066); let flow = parse_with(LinkType::ETHERNET, &raw, &config).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "STANAG 5066"); } }
The S_PDU
#![allow(unused)] fn main() { #[non_exhaustive] pub struct SisHeader { pub version: u8, /// Size of the primitive, type included. pub primitive_size: u16, pub pdu_type: u8, } #[non_exhaustive] pub struct SisPdu<'a> { pub header: SisHeader, pub pdu_type: PduType, // the named type pub primitive: SisPrimitive<'a>, /// The segment does not hold the whole announced primitive: the S_PDU /// goes on in the next segment. pub truncated: bool, // bytes of this S_PDU present in the buffer, read with consumed() } }
| Bytes | Field | Note |
|---|---|---|
| 0–1 | preamble | 90 EB, not kept |
| 2 | version | 0, the only one defined |
| 3–4 | primitive_size | type included: the S_PDU is 5 + primitive_size bytes |
| 5 | pdu_type | 1 to 27; SisPdu::pdu_type is the PduType |
| 6– | the primitive | primitive_size − 1 bytes, decoded into SisPrimitive |
A bind, as an HF Chat client and its node exchange it (tested):
#![allow(unused)] fn main() { #[test] fn a_bind_request_and_its_acceptance() { let raw = hex::decode(SIS_BIND_REQUEST_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let transport = flow.transport.as_ref().unwrap(); assert_eq!(transport.destination_port, Some(5066)); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "STANAG 5066"); let payload = transport.payload.unwrap(); assert_eq!(&payload[..2], &[0x90, 0xeb]); // the preamble let request = SisPdu::try_from(payload).unwrap(); assert_eq!(request.pdu_type, stanag5066::PduType::BindRequest); assert_eq!(request.header.version, 0); assert_eq!(request.header.primitive_size, 4); // type included assert_eq!(request.header.pdu_type, 1); assert!(!request.truncated); // 5 bytes of header and 4 of primitive: the whole segment. assert_eq!(request.consumed(), 9); assert_eq!(request.consumed(), payload.len()); let SisPrimitive::Bind { sap_id, rank, service_type, } = request.primitive else { panic!("expected a Bind primitive, got {:?}", request.primitive); }; assert_eq!((sap_id, rank), (5, 1)); // SAP 5: HF Chat, for tshark assert_eq!(service_type.transmission_mode, 1); // ARQ assert_eq!(service_type.delivery_confirmation, 1); // by the node assert!(service_type.in_order_delivery); assert!(!service_type.extended); // Frame 26, the node's answer: SAP 5 is bound, with an MTU of 250 bytes. let raw = hex::decode(SIS_BIND_ACCEPTED_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let accepted = SisPdu::try_from(payload).unwrap(); assert_eq!(accepted.pdu_type, stanag5066::PduType::BindAccepted); assert_eq!( accepted.primitive, SisPrimitive::BindAccepted { sap_id: 5, mtu: 250 } ); } }
Twenty-seven primitives, eight variants
Neighbouring primitives share a variant: the hard links (6 to 13), the management messages (18, 19), the data primitives and their confirmations (20 to 27).
#![allow(unused)] fn main() { #[non_exhaustive] pub enum SisPrimitive<'a> { /// S_BIND_REQUEST. Bind { sap_id: u8, rank: u8, service_type: ServiceType }, /// S_BIND_ACCEPTED. BindAccepted { sap_id: u8, mtu: u16 }, /// S_BIND_REJECTED and S_UNBIND_INDICATION. Rejected { reason: u8 }, /// S_HARD_LINK_*: `reason` for REJECTED, TERMINATED and REJECT, /// `remote_status` for ESTABLISHED and INDICATION; TERMINATE only /// carries the address. HardLink { reason: Option<u8>, remote_status: Option<u8>, link_type: Option<u8>, // two bits priority: Option<u8>, // two bits remote_sap_id: Option<u8>, remote_node: NodeAddress, }, /// S_SUBNET_AVAILABILITY. SubnetAvailability { status: u8, reason: u8 }, /// S_MANAGEMENT_MESSAGE_REQUEST and INDICATION. Management { message_type: u8, body: &'a [u8] }, /// S_UNIDATA_* and S_EXPEDITED_UNIDATA_*: `priority` for the requests and /// indications that are not expedited, `reason` for the rejections, /// `service_type`, `minimum_retransmissions` and `time_to_live` for the /// requests, `transmission_mode`, `source_sap_id` and `source` for the /// indications. Unidata { priority: Option<u8>, reason: Option<u8>, destination_sap_id: u8, destination: NodeAddress, service_type: Option<ServiceType>, minimum_retransmissions: Option<u8>, /// Twenty bits, LSB 2 s. time_to_live: Option<u32>, transmission_mode: Option<u8>, source_sap_id: Option<u8>, source: Option<NodeAddress>, /// Announced size of the U_PDU. u_pdu_size: u16, /// The U_PDU present in the segment: shorter than `u_pdu_size` /// when the S_PDU is truncated. u_pdu: &'a [u8], }, /// S_UNBIND_REQUEST, S_DATAFLOW_ON, S_DATAFLOW_OFF, S_KEEP_ALIVE. Empty, } }
The fixed fields of each type must be present, within the announced size and within the segment, or the S_PDU is PrimitiveTooShort; the minimum counts the bytes after the type byte.
| Code | PduType | SisPrimitive | Fixed bytes |
|---|---|---|---|
| 1 | BindRequest | Bind | 3 |
| 2 | UnbindRequest | Empty | 0 |
| 3 | BindAccepted | BindAccepted | 3 |
| 4, 5 | BindRejected, UnbindIndication | Rejected | 1 |
| 6, 12 | HardLinkEstablish, HardLinkAccept | HardLink: type, priority, remote SAP, node | 5 |
| 7 | HardLinkTerminate | HardLink: node only | 4 |
| 8, 11 | HardLinkEstablished, HardLinkIndication | HardLink: remote_status first | 6 |
| 9, 10, 13 | HardLinkRejected, HardLinkTerminated, HardLinkReject | HardLink: reason first | 6 |
| 14 | SubnetAvailability | SubnetAvailability | 2 |
| 15, 16, 17 | DataflowOn, DataflowOff, KeepAlive | Empty | 0 |
| 18, 19 | ManagementMessageRequest, ManagementMessageIndication | Management | 1 |
| 20, 24 | UnidataRequest, ExpeditedUnidataRequest | Unidata | 11 |
| 21, 25 | UnidataIndication, ExpeditedUnidataIndication | Unidata | 12 |
| 22, 26 | UnidataRequestConfirm, ExpeditedUnidataRequestConfirm | Unidata | 7 |
| 23, 27 | UnidataRequestRejected, ExpeditedUnidataRequestRejected | Unidata | 7 |
A bind request puts the SAP, the service access point the client binds to, in the high nibble of byte 6 and the rank in the low one, then the service type in byte 7; an acceptance puts the SAP in the high nibble of byte 6 and the MTU in bytes 7–8. The hard links other than S_HARD_LINK_TERMINATE pack their link type (two bits), priority (two bits) and remote SAP (four bits) in one byte, preceded by the status or the reason when the type has one, and followed by the node address; S_HARD_LINK_TERMINATE carries the node address alone.
Data primitives (20 to 27)
The data primitives are the traffic itself. Their layout, in bytes of the S_PDU:
| Field | Requests 20, 24 | Indications 21, 25 | Confirmations, rejections 22, 23, 26, 27 |
|---|---|---|---|
priority, high nibble | 6 (20 only) | 6 (21 only) | — |
reason, high nibble | — | — | 6 (23, 27 only) |
destination_sap_id, low nibble | 6 | 6 | 6 |
destination | 7–10 | 7–10 | 7–10 |
service_type | 11 | — | — |
minimum_retransmissions, high nibble | 12 | — | — |
time_to_live, 20 bits | 12–14 | — | — |
transmission_mode (high nibble), source_sap_id (low) | — | 11 | — |
source | — | 12–15 | — |
u_pdu_size | 15–16 | 16–17 | 11–12 |
u_pdu | 17– | 18– | 13– |
The time_to_live is raw, in units of two seconds (tshark labels it "x2 seconds"). Two records recur:
#![allow(unused)] fn main() { #[non_exhaustive] pub struct NodeAddress { /// Announced size, in half-bytes. pub size: u8, pub group: bool, /// The 28 address bits, 0x0a324202 for 10.50.66.2. pub address: u32, /// The four bytes, as they are. pub raw: [u8; 4], } #[non_exhaustive] pub struct ServiceType { /// Four bits: 1 ARQ, 2 non-ARQ (broadcast), 3 non-ARQ with errors. pub transmission_mode: u8, /// Two bits: 0 none, 1 confirmation by the node, 2 by the client. pub delivery_confirmation: u8, /// The delivery-order bit is zero: in-order delivery. pub in_order_delivery: bool, /// An extended field follows. pub extended: bool, pub raw: u8, } }
A node address is read on four bytes, like tshark does: three bits of size, one group bit, 28 bits of address. Its Display is tshark's dotted notation, the 29 low bits of the four bytes, group bit included, written like an IPv4 address.
The U_PDU of a complete S_PDU must be exactly u_pdu_size bytes, with one tolerance: an indication (21, 25) may carry four more, the counters a Rockwell Collins node (v2.1 and earlier) inserts before the U_PDU, which the decoder skips like tshark. Any other size is PrimitiveTooShort, even a longer U_PDU: expected is then the announced size and actual the bytes found. An indication in transmission mode 3, non-ARQ with errors, puts two lists before its U_PDU, the errored blocks then the missing ones, each a two-byte count followed by four bytes per block; the decoder skips them to reach the U_PDU.
An S_UNIDATA_REQUEST carrying ACP 142 (tested):
#![allow(unused)] fn main() { #[test] fn a_unidata_request_carrying_acp_142() { let raw = hex::decode(SIS_ACP142_REQUEST_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "STANAG 5066"); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let request = SisPdu::try_from(payload).unwrap(); assert_eq!(request.pdu_type, stanag5066::PduType::UnidataRequest); assert_eq!(request.header.primitive_size, 50); assert!(!request.truncated); assert_eq!(request.consumed(), payload.len()); // 55 bytes let SisPrimitive::Unidata { priority, reason, destination_sap_id, destination, service_type, minimum_retransmissions, time_to_live, source, u_pdu_size, u_pdu, .. } = request.primitive else { panic!("expected a Unidata primitive, got {:?}", request.primitive); }; assert_eq!((priority, reason), (Some(0), None)); // a request has no reason assert_eq!(destination_sap_id, 2); // for tshark, the STANAG 4406 annex E client assert_eq!(destination.to_string(), "10.50.66.2"); assert_eq!((destination.size, destination.group), (7, false)); assert_eq!(destination.address, 0x0a32_4202); assert_eq!(service_type.unwrap().transmission_mode, 2); // non-ARQ assert_eq!((minimum_retransmissions, time_to_live), (Some(0), Some(0))); assert!(source.is_none()); // only indications name a source assert_eq!((u_pdu_size, u_pdu.len()), (38, 38)); // The U_PDU stays raw: an ACP 142 message behind a client transport // header whose application identifier is 0x2000. assert_eq!(&u_pdu[4..6], &[0x20, 0x00]); } }
Stateless: one S_PDU at a time
An S_PDU and a TCP segment have no reason to coincide: one S_PDU may be split over several segments, and one segment may hold several S_PDUs. The HF Chat client and node of the corpus send every data primitive in two segments, its header and fixed fields then its U_PDU, even when the whole S_PDU is only 29 bytes; the ACP 142 capture packs three S_PDUs of 2 065 bytes into one segment. With no reassembly, the decoder follows four rules:
- An S_PDU that overflows its segment is accepted and flagged
truncated. Its fixed fields are decoded, andu_pduis what the segment holds, possibly nothing. The fixed fields must all be there: a segment that cuts them isPrimitiveTooShort, truncated or not. - A continuation segment is not SIS. It does not start with the preamble, so
try_fromrefuses it (InvalidPreamble, orTruncatedbelow six bytes), and the segment is labelled by whatever else matches:"Unknown", for the five of the corpus. - What follows a complete S_PDU must start another one: nothing, or as many bytes of
90 EB 00as remain, up to three. Anything else isUnexpectedTrailingBytes, and the segment is not labelled STANAG 5066. consumed()says where the next S_PDU starts: the bytes of this S_PDU present in the buffer, header included, which for a truncated S_PDU is the whole buffer. A caller reads the next S_PDU at&payload[pdu.consumed()..].
An S_UNIDATA_INDICATION split over two segments (tested):
#![allow(unused)] fn main() { #[test] fn a_split_s_pdu_is_decoded_on_its_first_segment() { let raw = hex::decode(SIS_INDICATION_FIRST_SEGMENT_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "STANAG 5066"); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let indication = SisPdu::try_from(payload).unwrap(); assert_eq!(indication.pdu_type, stanag5066::PduType::UnidataIndication); // 5 + 30 = 35 bytes announced, 18 in this segment. assert_eq!(indication.header.primitive_size, 30); assert_eq!(payload.len(), 18); assert!(indication.truncated); assert_eq!(indication.consumed(), 18); // The fixed fields are all in this segment, the U_PDU is not. let SisPrimitive::Unidata { priority, destination_sap_id, destination, transmission_mode, source_sap_id, source, u_pdu_size, u_pdu, .. } = indication.primitive else { panic!("expected a Unidata primitive, got {:?}", indication.primitive); }; assert_eq!((priority, destination_sap_id), (Some(0), 5)); assert_eq!(destination.to_string(), "5.100.100.2"); assert_eq!((transmission_mode, source_sap_id), (Some(1), Some(5))); // ARQ assert_eq!(source.unwrap().to_string(), "5.100.100.1"); assert_eq!(u_pdu_size, 17); assert!(u_pdu.is_empty()); // Frame 30, the next segment: the 17 bytes of the U_PDU. Without a // preamble they are not an S_PDU, and the segment stays "Unknown". let raw = hex::decode(SIS_INDICATION_CONTINUATION_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); assert_eq!(payload, b"<0> Hello there.\n"); assert_eq!( SisPdu::try_from(payload), Err(Stanag5066ParseError::InvalidPreamble(*b"<0")) ); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "Unknown"); } }
and the only segment of the corpus that holds several S_PDUs, three S_UNIDATA_REQUESTs walked with consumed (tested):
#![allow(unused)] fn main() { #[test] fn consumed_walks_the_s_pdus_of_a_segment() { let raw = hex::decode(SIS_THREE_REQUESTS_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "STANAG 5066"); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); assert_eq!(payload.len(), 6195); // `try_from` decodes the first S_PDU; `consumed` says where the next // one starts. let mut rest = payload; let mut lengths = Vec::new(); while !rest.is_empty() { let pdu = SisPdu::try_from(rest).unwrap(); assert_eq!(pdu.pdu_type, stanag5066::PduType::UnidataRequest); assert!(!pdu.truncated); let SisPrimitive::Unidata { destination, u_pdu_size, u_pdu, .. } = pdu.primitive else { panic!("expected a Unidata primitive, got {:?}", pdu.primitive); }; assert_eq!(destination.to_string(), "10.50.66.2"); assert_eq!((u_pdu_size, u_pdu.len()), (2048, 2048)); lengths.push(pdu.consumed()); rest = &rest[pdu.consumed()..]; } assert_eq!(lengths, [2065, 2065, 2065]); } }
Validations
All of them are Stanag5066ParseError, in packet_parser::errors::application::stanag5066:
| Error | When |
|---|---|
Truncated { expected, actual } | fewer than 6 bytes, the header and the type |
InvalidPreamble([u8; 2]) | the first two bytes are not 90 EB |
UnsupportedVersion(u8) | a version other than 0 |
EmptyPrimitive | a primitive_size of 0, which cannot hold the type |
ReservedPduType(u8) | a type other than 1 to 27 |
PrimitiveTooShort { pdu_type, expected, actual } | the fixed fields of the type are missing, or a complete S_PDU holds a U_PDU of another size than announced |
UnexpectedTrailingBytes { trailing } | after a complete S_PDU, bytes that do not start 90 EB 00 |
Like every application decoder, a failure is not a corruption: the segment goes on to the next rules of the table, and nothing goes to corrupted.
Oracle: 34 segments, without reassembly
The golden test tests/stanag5066_golden.rs runs the four captures of pcaps_exemple/protocols/stanag5066/ and compares every segment with tshark 4.6.6 without TCP reassembly (tcp.desegment_tcp_streams:FALSE), the view of a stateless parser, frozen in tests/data/stanag5066_tshark_oracle.tsv by tools/stanag5066_oracle.sh: S_PDU types, primitive sizes, node addresses, SAPs, U_PDU sizes, transmission modes, TTLs, ranks, MTUs and reasons. The 34 segments where tshark sees SIS are labelled "STANAG 5066" and decoded alike, 36 S_PDUs of 13 of the 27 types; the 5 continuation segments, where tshark sees no SIS without reassembly, come out "Unknown"; 5 S_PDUs split between two segments are decoded on their first one and flagged truncated, three in S5066-HFChat-1.pcap (an indication, a request, a confirmation) and two in S5066-HFChat-Rejected.pcap (a request, a rejection). The other 47 frames are TCP segments without payload.
| Capture | Frames (with an S_PDU) | Content | Origin |
|---|---|---|---|
S5066-HFChat-1.pcap | 44 (6) | an HF Chat client and its node, the NATO C3 Agency test bench, 2005 | Wireshark wiki |
S5066-HFChat-Rejected.pcap | 19 (5) | the same bench, an S_UNIDATA_REQUEST rejected with reason 3 | Wireshark wiki |
S5066-Expedited.pcap | 13 (13) | expedited data and hard links on the loopback, 2006 | Wireshark wiki |
wireshark_10827_sis_acp142.pcap | 10 (10) | ACP 142 over SIS on the loopback, 2015 | Wireshark issue 10827 |
In the golden histogram of the whole corpus, "STANAG 5066" went from 0 to 34 with 11.6.0, all taken from "Unknown". The fuzz target parse_stanag5066 runs nightly: no panic, and every S_PDU it decodes consumes no more than the input, borrows its U_PDU from the input, and, when truncated, consumes the rest of it.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- No reassembly: the U_PDU of a split S_PDU is what its first segment holds, and the continuation segments come out
"Unknown". A caller that tracks the TCP stream hasu_pdu_sizeto rebuild it. - The U_PDU stays raw: the ACP 142 (P_MUL) or STANAG 4406 annex E message it carries, behind its client transport header, is not decoded; neither is the body of a management message.
- Skipped, not exposed: the block lists of an indication in mode 3, and the minimum number of retransmissions that follows the service type of an S_BIND_REQUEST (the data requests do expose theirs).
- Values are numbers: SAP identifiers, reasons and statuses are not named.
- The DTS layer below the SIS is out of scope: the wiki's DTS captures are LINKTYPE 237, which the crate does not read, or DTS encapsulated on TCP 5067 to 5069, which is not SIS.
TLS
Transport Layer Security, as far as its record layer: the five bytes that precede every record, from TLS 1.0 to TLS 1.3. The module is packet_parser::parse::application::protocols::tls, with TlsPacket for one record and parse_tls_records for the records of a segment. Its errors are TlsError, in packet_parser::errors::application::tls.
The crate reads the envelope and nothing inside it. It does not decode the handshake, so it extracts no server name and no cipher suite, and it decrypts nothing.
Detection: one blind rule on TCP
Rule 61 of the dispatch table has a TCP guard, no port, and TlsPacket::try_from as its probe. A segment is "TLS" when it starts with a record header and holds the whole record:
- the first byte is a content type, 20 to 24;
- the next two are a version, 3.1 to 3.4;
- the length that follows fits in what is left of the segment.
The probe looks at the first record only. What follows it in the segment is not checked, so the label says "this segment starts with a TLS record".
Port 443 plays no part. TLS is where its handshake is: on 443, on 8443, on a mail port after STARTTLS, on a database port after an SSLRequest. The rule comes late in the table, after every port rule and most blind ones, because five bytes are thin evidence next to a decoder that checks a whole message.
That order explains a label that surprises at first. On port 3389, the RDP rule is tried first; once the server has selected TLS or CredSSP, the segments no longer start with a TPKT header, the RDP probe refuses them, and rule 61 labels them "TLS". The same happens to PostgreSQL after an accepted SSLRequest. The label follows the bytes of each segment, not the history of the connection.
A Client Hello, on port 443 and off it (tested):
#![allow(unused)] fn main() { #[test] fn a_client_hello_is_a_record_and_nothing_more() { let raw = hex::decode(TLS_CLIENT_HELLO_HEX).unwrap(); let flow = parse(LinkType::RAW, &raw).unwrap(); assert_eq!(label(&flow), Some("TLS")); // 46800 -> 443 let payload = flow.transport.as_ref().unwrap().payload.unwrap(); let record = TlsPacket::try_from(payload).unwrap(); assert_eq!(record.content_type, TlsContentType::Handshake); // The record says 3.1, TLS 1.0: a TLS 1.2 client writes it there for // old middleboxes. The version it offers is inside the handshake. assert_eq!(record.version.to_string(), "TLS 1.0"); assert_eq!(record.length, 224); assert_eq!(payload.len(), 5 + 224); // one record fills the segment // The handshake is not decoded. Its bytes are there: type 1, Client // Hello, then the version 3.3, and further on the server name. assert_eq!(record.payload[0], 1); assert_eq!(record.payload[4..6], [3, 3]); assert!(record.payload.windows(11).any(|w| w == b"example.com")); // The rule has no port: the same segment is TLS anywhere. let moved = with_ports(&raw, 40000, 40001); assert_eq!(label(&parse(LinkType::RAW, &moved).unwrap()), Some("TLS")); } }
The record
#![allow(unused)] fn main() { #[non_exhaustive] pub struct TlsPacket<'a> { pub content_type: TlsContentType, // ChangeCipherSpec, Alert, Handshake, // ApplicationData, Heartbeat pub version: TlsVersion, // major and minor, displayed as "TLS 1.2" pub length: u16, // the length the header declares pub payload: &'a [u8], // that many bytes, borrowed } }
The version of the record header is not the version of the session. A TLS 1.2 client writes 3.1 in its first record, for the middleboxes that refuse anything newer, and TLS 1.3 writes 3.3 in every record: the negotiated version is in the handshake, which the crate does not read. TlsVersion displays what the header says.
The record version may be 3.0 since 13.1.0, displayed SSL 3.0. RFC 5246 (appendix E.1) lets a client send its Client Hello in a 3.0 record to reach an old server, and SSL 3.0 uses it itself. Until then such records came out "Unknown", even on TCP 443 #300.
payload is the record as it is on the wire. For a handshake before the keys are set, it is cleartext: the Client Hello of the example carries the name example.com in its bytes. After the Change Cipher Spec, or in every TLS 1.3 record after the Server Hello, it is ciphertext.
parse_tls_records walks a segment and returns the records that are whole. It stops without an error at the first record that is cut, or at the first bytes that are not a record header.
A record cut by the segment
A record can be up to 16 KiB of data, and a certificate chain rarely fits in one segment. The first segment holds the record header and declares more bytes than it carries; the following ones start in the middle of the record.
Since the probe wants the first record whole, the outcome depends on where the cut falls:
| The segment starts with | Label |
|---|---|
| a whole record, whatever follows | "TLS" |
| a record header whose record is cut | "Unknown" |
| the middle of a record | "Unknown", unless the bytes happen to form a record header |
Frames 2 and 3 of tls12-dsb.pcapng show the first and the third row (tested):
#![allow(unused)] fn main() { #[test] fn a_record_cut_by_the_segment_hides_the_next_segment() { // The server answers with two records. The first fits in the segment. let raw = hex::decode(TLS_SERVER_HELLO_HEX).unwrap(); let flow = parse(LinkType::RAW, &raw).unwrap(); assert_eq!(label(&flow), Some("TLS")); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); assert_eq!(payload.len(), 1448); let records = parse_tls_records(payload); assert_eq!(records.len(), 1); // the Server Hello, 5 + 112 bytes assert_eq!(records[0].length, 112); // The second starts right after it and declares more than is left. let next = &payload[117..]; assert_eq!(next[0], 22); // a handshake record: the Certificate let declared = usize::from(u16::from_be_bytes([next[3], next[4]])); assert!(declared > next.len() - 5); assert!(TlsPacket::try_from(next).is_err()); // Its end is in the next segment, which starts in the middle of a // certificate: no record header, no label. let raw = hex::decode(TLS_CERTIFICATE_REST_HEX).unwrap(); let flow = parse(LinkType::RAW, &raw).unwrap(); assert_eq!(label(&flow), Some("Unknown")); } }
A record of TLS 1.2 can reach 18 437 bytes with its header, more than the 18 432 bytes the probes used to read. Since 11.7.0 the TLS probe reads the whole segment, so a record of that size in one large segment is recognized (#185).
Validations
| Bytes | Field | Check | Error |
|---|---|---|---|
| 0–4 | Record header | the buffer holds at least 5 bytes | TlsError::TooShort |
| 0 | Content type | 20 to 24 | InvalidContentType, with the byte |
| 1–2 | Version | 3.1, 3.2, 3.3 or 3.4 | InvalidVersion { major, minor } |
| 3–4 | Length | the buffer holds that many bytes after the header | InconsistentLength { declared, available } |
The length is not compared with the maximum a TLS version allows.
Oracle: counts and digests
TLS has no field-by-field oracle. tests/tshark_regression.rs compares, for the seven captures of pcaps_exemple/protocols/tls/, the frames the crate labels "TLS" with the frames of tshark -Y tls: 587 frames, a count and a digest of the frame numbers per capture. The differences are named:
| Capture | Frames tshark reports and the crate does not | Why |
|---|---|---|
tls1.3-ech.pcapng | 20, 30, 45, 67, 74 | records over two to four segments |
tls12-dsb.pcapng | 3 | the second segment of a record, the example above |
dump.pcapng | 964, 1069, 1084 | Client Hellos in the SSLv2-compatible format, which is not a TLS record |
tls12-dsb.pcapng carries its own keys, and tshark decrypts the HTTP exchange in it. The crate labels those frames "TLS". The golden histogram counts 1 294 TLS labels.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- The handshake. No message is decoded: no server name, no ALPN, no cipher suite, no certificate. A consumer that wants the SNI reads it in
payload. - The negotiated version. The label does not tell TLS 1.2 from TLS 1.3, and the record version does not either.
- The SSLv2-compatible Client Hello. It has no record header.
- DTLS. The rule has a TCP guard, and the DTLS record header is not the TLS one.
- A record over several segments. Only a segment that starts with a whole record is labelled.
- Decryption. Never, even when the capture holds the keys.
Valmet DNA
Valmet DNA (Metso DNA), the process network of the distributed control systems of Metso and Valmet, added in 11.8.0 (8ffdec1, released by PR #229), the only decoder of that release. On the network the crate was built from, the nodes send UDP datagrams to a multicast group: periodic status telegrams, messages that name a tag, and a beacon. The module is packet_parser::parse::application::protocols::valmet_dna, its error packet_parser::errors::application::valmet_dna::ValmetDnaParseError.
Observed, not specified
The protocol is proprietary: there is no public specification and no public dissector, and tshark has none. The decoder is built on the observation of traffic alone, one capture taken on the mirror port of a process network in operation and anonymized in pcaps_exemple/protocols/valmet_dna/ of the crate, without code or documentation from the vendor. It reads: it rebuilds no control logic and emits nothing. The names of the fields are those of the observation, not those of the vendor. Nothing on this page comes from the vendor either.
What the capture establishes, what the crate infers from it, and what stays unknown:
| Point | Status |
|---|---|
The magic AB 01, the length equal to the datagram minus two, the two families and their sizes | established: true of every message of the capture |
| The node address and the multicast group in the status telegram | established: equal to the IP source and the IP destination of every telegram |
The node number, low byte of the source node 0x80NN | established: equal on every telegram |
| The order of the fields of the BCD clock | established on the original capture, which is not in the corpus (see the clock) |
| The two counters of the status telegram, the second repeating the first of the previous telegram | established: checked telegram after telegram; microseconds, since they advance by about 640 000 every 640 ms |
The tag length written twice, the tag that ends the datagram, the form :e:<class>:<path> | established on the 400 tag messages, 360 of which have the readable form |
The destination 0x00FF as "all nodes" | inferred: every frame observed carries it, and all are multicast |
| The convention of the weekday | unknown: one day observed, two conventions fit |
| 87 of the 126 bytes of the status telegram, 56 of the 72 bytes of the tag message header, 16 of the 42 bytes of the beacon | not identified, kept as bytes |
| What the classes, the beacon's code and counter, and any other family mean | unknown |
The capture
The corpus capture, valmet-dna-multicast-anon.pcap, is the first twelve seconds of DNA traffic of a 212-second capture made by the maintainer on 2026-11-03. Its 720 UDP datagrams all go to the multicast group 239.0.171.1, whose last two bytes, 171 and 1, are the magic AB 01:
- 719 on UDP 2517 → 2517: 319 status telegrams of 126 bytes, sent every 640 ms by each of 17 nodes,
0x8008to0x802D, 18 or 19 each; and 400 tag messages of 82 to 116 bytes from 14 of those nodes; - 1 on UDP 4516 → 4517: the 42-byte beacon, frame 591.
The anonymization renumbered the unicast MAC and IPv4 addresses (the IPv4 ones into 10.0.2.0/24, with the node address inside the payload), substituted the site-specific part of the tags letter by letter and digit by digit, and rewrote the clocks from the timestamp of their frame, rebased to 2020-01-01 00:00:00 UTC. Everything else in the payloads, headers, families, lengths, counters and bytes not identified, is identical byte for byte to the original, according to the folder's SOURCE.md.
Detection: three ports, then a blind probe
As for PTP on UDP, the pipeline gives the datagram a label, "Valmet DNA", and nothing more: the decode is ValmetDnaPacket::try_from, or TimeBeacon::try_from for the beacon, on the transport payload. No port is registered in the protocol's name; 2517, 4516 and 4517 are the ports the capture shows. The crate therefore has three routes, from the most tolerant to the strictest:
| Where | Probe | Accepts |
|---|---|---|
| UDP 2517, 4516 or 4517, on either side | ProbeId::ValmetDna | a message with a coherent header, of a known family at its exact size or of an unknown one, or a beacon |
a port declared with ParseConfig::decode_as(port, DecodeAsProtocol::ValmetDna) | ProbeId::ValmetDna | the same |
| any other UDP port | ProbeId::ValmetDnaBlind | a message of one of the two known families, at its exact size |
In the table of src/parse/dispatch/rules.rs:
#![allow(unused)] fn main() { // among the port rules, after BACnet/IP: UDP 2517 for the AB 01 messages, // 4516 -> 4517 for the beacon, the observed ports. On these ports an unknown // message family is accepted with its body as bytes; elsewhere, the blind // probe below only accepts the two known families. port_rule(ApplicationProtocol::ValmetDna, Guard::Udp, is_valmet_dna_udp_port, ProbeId::ValmetDna), // ... // --- blind cascade --- rule(ApplicationProtocol::Ntp, Guard::Udp, ProbeId::NtpBlind), rule(ApplicationProtocol::Rtps, Guard::Udp, ProbeId::Rtps), // Magic AB 01, a length equal to the datagram minus two and a known family // at its exact size: more than 64 bits of constraint, enough to do without // the port. rule(ApplicationProtocol::ValmetDna, Guard::Udp, ProbeId::ValmetDnaBlind), rule(ApplicationProtocol::Asterix, Guard::Udp, ProbeId::Asterix), }
with the probes, both on the whole datagram and not on its first PROBE_CAP bytes, since the length must equal the datagram minus two:
#![allow(unused)] fn main() { ProbeId::ValmetDna => ValmetDnaPacket::is_port_udp_match(payload), ProbeId::ValmetDnaBlind => ValmetDnaPacket::is_blind_udp_match(payload), impl ValmetDnaPacket<'_> { pub(crate) fn is_port_udp_match(payload: &[u8]) -> bool { ValmetDnaPacket::try_from(payload).is_ok() || TimeBeacon::try_from(payload).is_ok() } pub(crate) fn is_blind_udp_match(payload: &[u8]) -> bool { ValmetDnaPacket::try_from(payload).is_ok_and(|packet| packet.kind.is_some()) } } }
The blind rule comes right after RTPS and before ASTERIX in the blind cascade, and classify_payload, given UDP and no port (None, None), reaches it there. The beacon has no blind route: off its ports, it needs a declared port. Decode As resolves DecodeAsProtocol::ValmetDna to (ApplicationProtocol::ValmetDna, Guard::Udp, ProbeId::ValmetDna), the probe of the port rule, behind the same UDP guard: a unit test of dispatch/tests.rs checks that a status telegram on TCP 2517 is not Valmet DNA, Decode As included.
Frames 1, 9 and 591 moved to UDP 40000 → 40001: the status telegram and the tag message keep their label, the beacon needs Decode As (tested):
#![allow(unused)] fn main() { #[test] fn three_ports_then_a_blind_probe_for_the_two_known_families() { let default = ParseConfig::new(); let declared = ParseConfig::new().decode_as(40_001, DecodeAsProtocol::ValmetDna); let label_of = |frame: &[u8], config: &ParseConfig| { let flow = parse_with(LinkType::ETHERNET, frame, config).unwrap(); flow.application.as_ref().map(|application| application.protocol.label()) }; let off_port = |frame: &[u8]| { let mut moved = frame.to_vec(); moved[34..38].copy_from_slice(&[0x9c, 0x40, 0x9c, 0x41]); // 40000 -> 40001 moved }; let status = hex::decode(STATUS_TELEGRAM_HEX).unwrap(); let tag = hex::decode(TAG_MESSAGE_HEX).unwrap(); let beacon = hex::decode(BEACON_HEX).unwrap(); // Frames 1 and 9 moved to UDP 40000 -> 40001: the magic, the length // and the exact size of a known family are enough. assert_eq!(label_of(&off_port(&status), &default), Some("Valmet DNA")); assert_eq!(label_of(&off_port(&tag), &default), Some("Valmet DNA")); // `classify_payload`, given the transport and no port, agrees. let blind = classify_payload(TransportProtocol::Udp, None, None, &status[DATAGRAM..]).unwrap(); assert_eq!(blind.protocol, ApplicationProtocol::ValmetDna); // The beacon is recognized on its ports, or on a declared port. assert_eq!(label_of(&beacon, &default), Some("Valmet DNA")); assert_eq!(label_of(&off_port(&beacon), &default), Some("Unknown")); assert_eq!(label_of(&off_port(&beacon), &declared), Some("Valmet DNA")); } }
The header
#![allow(unused)] fn main() { #[non_exhaustive] pub struct ValmetDnaPacket<'a> { /// The sending node: 0x80NN on every frame observed, NN the node number. pub source_node: u16, /// 0x00FF on every frame observed, all multicast. pub destination: u16, /// The declared length: the datagram minus two. pub length: u16, /// The message family, as read. pub kind_code: u32, /// The named family, when MessageKind knows it. pub kind: Option<MessageKind>, /// Everything after the 12-byte header, as is. pub body: &'a [u8], pub message: ValmetDnaMessage<'a>, } #[non_exhaustive] pub enum MessageKind { /// 0x00000FFF: the periodic status telegram, 126 bytes. Status, /// 0x001E00D0: the tag message. Tag, } #[non_exhaustive] pub enum ValmetDnaMessage<'a> { Status(StatusTelegram), Tag(TagMessage<'a>), /// Unknown family: the body is in ValmetDnaPacket::body. Unknown, } }
| Bytes | Field | Note |
|---|---|---|
| 0–1 | magic | AB 01, checked, not kept |
| 2–3 | source_node | 0x80NN on every frame of the capture; node_number() returns NN |
| 4–5 | destination | 0x00FF on every frame of the capture: "all nodes", likely |
| 6–7 | length | the bytes after the magic: the datagram minus two, exactly |
| 8–11 | kind_code | MessageKind::from_code names 0x00000FFF and 0x001E00D0 |
| 12– | body | everything after the header, the named fields included |
Every integer is read big-endian, except the two words of the clock. The family decides the rest: a status telegram, a tag message, or Unknown.
The status telegram
The family 0x00000FFF, 126 bytes exactly, sent by each node every 640 ms: the frame timestamps of the capture, whose gaps the anonymization kept, put two telegrams of a node between 638.8 and 642.3 ms apart.
#![allow(unused)] fn main() { #[non_exhaustive] pub struct StatusTelegram { /// The node's IPv4 address: the IP source on every frame observed. pub node_ip: Ipv4Addr, /// The node's clock, when its ten bytes form a valid date. pub clock: Option<DnaClock>, /// The low byte of ValmetDnaPacket::source_node on every frame observed. pub node_number: u8, /// The network's multicast group: the IP destination. pub multicast_group: Ipv4Addr, /// A 32-bit counter in microseconds, modulo 2^32. pub tick: u32, /// The tick of the node's previous telegram. pub previous_tick: u32, } }
| Bytes | Field | What ties it down |
|---|---|---|
| 0–11 | header | family 0x00000FFF, length 124 |
| 12–35 | not identified | |
| 36–39 | node_ip | equal to the IP source of all 319 telegrams |
| 40–41 | not identified | |
| 42–51 | clock | a DnaClock |
| 52–57 | not identified | |
| 58 | node_number | equal to the low byte of source_node on all 319 |
| 59–69 | not identified | |
| 70–73 | multicast_group | equal to the IP destination |
| 74–105 | not identified | |
| 106–109 | tick | see the counters |
| 110–113 | previous_tick | the tick of the node's previous telegram |
| 114–125 | not identified |
The telegram of node 0x801D, frame 1 of the capture (tested):
#![allow(unused)] fn main() { #[test] fn a_status_telegram_carries_its_node_a_clock_and_two_counters() { // Frame 1, UDP 2517 -> 2517: the pipeline gives the label, the // decoder reads the datagram, borrowed from the frame. let raw = hex::decode(STATUS_TELEGRAM_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("Valmet DNA")); let internet = flow.internet.as_ref().unwrap(); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); assert_eq!(payload.len(), 126); // The header: the magic AB 01 (checked, not kept), node 0x801D, // destination 0x00FF, a length of 124, the datagram minus two, and // the family 0x00000FFF. let packet = ValmetDnaPacket::try_from(payload).unwrap(); assert_eq!((packet.source_node, packet.destination, packet.length), (0x801d, 0x00ff, 124)); assert_eq!(packet.kind_code, 0x0000_0fff); assert_eq!(packet.kind, Some(MessageKind::Status)); assert_eq!(packet.node_number(), 0x1d); assert_eq!(packet.body, &payload[12..]); // everything after the header, as is let ValmetDnaMessage::Status(status) = packet.message else { panic!("expected a status telegram, got {:?}", packet.message); }; // What the golden test checks on the 319 telegrams of the capture: // the node address is the IP source, the group the IP destination, // the node number the low byte of the node identifier. assert_eq!(status.node_ip, Ipv4Addr::new(10, 0, 2, 1)); assert_eq!(internet.source, Some(IpAddr::V4(status.node_ip))); assert_eq!(status.multicast_group, Ipv4Addr::new(239, 0, 171, 1)); assert_eq!(internet.destination, Some(IpAddr::V4(status.multicast_group))); assert_eq!(status.node_number, 29); assert_eq!(status.node_number, packet.node_number()); // Two 32-bit counters, 640 239 apart over one period of 640 ms: // microseconds. `previous_tick` is the `tick` of the node's previous // telegram, which the capture does not hold for frame 1. assert_eq!((status.tick, status.previous_tick), (0x540f_5bf1, 0x5405_9702)); assert_eq!(status.tick.wrapping_sub(status.previous_tick), 640_239); // The clock, rewritten by the anonymization from the frame's rebased // timestamp: 2020-01-01 00:00:00.0000, weekday 3. let clock = status.clock.expect("a valid date"); assert_eq!((clock.year, clock.month, clock.day, clock.weekday), (2020, 1, 1, 3)); assert_eq!((clock.hour, clock.minute, clock.second, clock.fraction), (0, 0, 0, 0)); assert_eq!(clock.microseconds_of_day(), 0); } }
The BCD clock
The status telegram and the beacon carry the same ten-byte clock, every digit in BCD, two digits per byte:
#![allow(unused)] fn main() { #[non_exhaustive] pub struct DnaClock { /// Fraction of a second, in units of 100 µs (0 to 9999). pub fraction: u16, pub second: u8, pub minute: u8, pub hour: u8, pub weekday: u8, pub day: u8, pub month: u8, pub year: u16, } }
| Bytes | Field | Note |
|---|---|---|
| 0–1 | fraction | two BCD bytes, low byte first: 86 95 is 9586, in units of 100 µs |
| 2 | second | 0 to 59 |
| 3 | minute | 0 to 59 |
| 4 | hour | 0 to 23 |
| 5 | weekday | 0 to 7 |
| 6 | day | 1 to 31 |
| 7 | month | 1 to 12 |
| 8–9 | year | two BCD bytes, low byte first: 26 20 is 2026; no range |
How the order was established. On the original capture, not on the corpus one: the seconds go from 59 to 00 with a carry into the minutes, the fraction advances by 6 400 per telegram, the 640 ms of the period, and the hour and the weekday are those of the day of the capture. The corpus capture cannot show this again. Its clocks were rewritten from the timestamps of the frames, which start at midnight on 2020-01-01 and last twelve seconds: no minute rolls over, and the year is 20 20, which does not show the order of its two bytes. On the original capture, the clocks of the nodes were twenty-nine minutes off the official time, by the same amount on every node: the clock dates the exchanges between nodes, not the outside world.
The weekday was 2 on the day of the original capture, a Tuesday: Monday is 1 (ISO 8601), or Sunday is 0. With a single day observed, the two conventions agree, and the crate does not choose. The rewritten clocks of the corpus say 3, 2020-01-01 being a Wednesday.
DnaClock::from_bytes reads the first ten bytes of its argument and returns None if there are fewer, if a nibble is not a decimal digit, or if a field is out of its range: an unset clock, not a decoding error. A telegram or a beacon with such a clock still decodes, with clock: None. microseconds_of_day() gives the microseconds since midnight, to compare two clocks of the same day.
The clock of the beacon, the vector of the crate's unit test for the year, and an unset clock (tested):
#![allow(unused)] fn main() { #[test] fn the_clock_is_ten_bcd_bytes_with_two_little_endian_words() { // The beacon of frame 591 carries the clock at offset 28 of its // datagram. let raw = hex::decode(BEACON_HEX).unwrap(); let bytes = &raw[DATAGRAM + 28..DATAGRAM + 38]; assert_eq!(bytes, [0x86, 0x95, 0x09, 0x00, 0x00, 0x03, 0x01, 0x01, 0x20, 0x20]); let clock = DnaClock::from_bytes(bytes).unwrap(); // The fraction is a word, low byte first: 86 then 95 is 9586, in // units of 100 us. Then second, minute, hour, weekday, day and // month, one BCD byte each, and the year, low byte first. assert_eq!(clock.fraction, 9586); assert_eq!((clock.second, clock.minute, clock.hour), (9, 0, 0)); assert_eq!((clock.weekday, clock.day, clock.month, clock.year), (3, 1, 1, 2020)); assert_eq!(clock.microseconds_of_day(), 9_958_600); // Every clock of the capture has the year 20 20, which cannot show // the order of its two bytes. The vector of the crate's own unit // test does: 26 20 is 2026. let unit_test = [0x70, 0x08, 0x37, 0x52, 0x10, 0x02, 0x03, 0x11, 0x26, 0x20]; let clock = DnaClock::from_bytes(&unit_test).unwrap(); assert_eq!((clock.year, clock.month, clock.day, clock.weekday), (2026, 11, 3, 2)); assert_eq!((clock.hour, clock.minute, clock.second, clock.fraction), (10, 52, 37, 870)); // A nibble above 9, a field out of range or fewer than ten bytes is // not a clock. let mut not_bcd = unit_test; not_bcd[2] = 0x3a; assert_eq!(DnaClock::from_bytes(¬_bcd), None); assert_eq!(DnaClock::from_bytes(&[0; 10]), None); // day 0, month 0 assert_eq!(DnaClock::from_bytes(&unit_test[..9]), None); // In a telegram, an invalid clock is `None`, not a refusal: frame 1 // with ten zero bytes in place of its clock still decodes. let status = hex::decode(STATUS_TELEGRAM_HEX).unwrap(); let mut unset = status[DATAGRAM..].to_vec(); unset[42..52].fill(0); let packet = ValmetDnaPacket::try_from(unset.as_slice()).unwrap(); let ValmetDnaMessage::Status(telegram) = packet.message else { panic!("expected a status telegram, got {:?}", packet.message); }; assert_eq!(telegram.clock, None); } }
The two counters
tick and previous_tick are two 32-bit counters, read big-endian. previous_tick repeats the tick of the same node's previous telegram: the golden test checks it on the 302 telegrams of the capture that have a predecessor. From one telegram to the next, tick advances by about 640 000, 639 111 to 642 481 on the capture, over a period of 640 ms: microseconds, modulo 2³². The crate does not interpret them further; what they count from is not known.
The tag message
The family 0x001E00D0: a fixed 72-byte header, then a tag that ends the datagram.
#![allow(unused)] fn main() { #[non_exhaustive] pub struct TagMessage<'a> { /// The declared tag length, equal to tag.len(). pub tag_length: u16, /// The tag, as is: `:e:<class>:<path>` when it is readable, ten bytes /// that are not text otherwise. pub tag: &'a [u8], } impl<'a> TagMessage<'a> { pub fn tag_text(&self) -> Option<&'a str>; // the tag, when it is valid UTF-8 pub fn class(&self) -> Option<&'a str>; // <class> of `:e:<class>:<path>` pub fn path(&self) -> Option<&'a str>; // <path> of the same form } }
| Bytes | Field | Note |
|---|---|---|
| 0–11 | header | family 0x001E00D0 |
| 12–27 | not identified | |
| 28–29 | tag_length | |
| 30–69 | not identified | |
| 70–71 | the tag length, again | must equal the first |
| 72– | tag | tag_length bytes, up to the end of the datagram |
The decoder checks that the datagram holds the 72 bytes of the header, that the two lengths are equal, and that 72 plus the tag length is the datagram; the tag is borrowed, not copied. An empty tag, two zero lengths in 72 bytes, is accepted.
The tags of the capture start with :e:. 360 of the 400 are readable text of the form :e:<class>:<path>, with a class of two letters: di 286 times, pr 57, sn 9, hw 6 and li 2. class() and path() answer when the text starts with :e:, has a non-empty class and a colon after it; the path may be empty. The 40 others are ten bytes that are not UTF-8: frame 2, in the crate's unit tests, is :e:A2, then 0xC1, 1, a NUL and 0xFE 0xFF; tag_text, class and path are None for them, and tag keeps the bytes. The crate calls the two letters a class, after their place in the tag; what they mean is not known. In the corpus, the path is the anonymized one: the marker, the class, the delimiters and the length are the original ones, the letters and digits of the path are not.
A tag of class di sent by node 0x8028, frame 9 of the capture (tested):
#![allow(unused)] fn main() { #[test] fn a_tag_message_borrows_its_tag_and_splits_the_readable_form() { // Frame 9: 115 bytes, the fixed 72-byte header and a 43-byte tag. let raw = hex::decode(TAG_MESSAGE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("Valmet DNA")); let payload = flow.transport.as_ref().unwrap().payload.unwrap(); assert_eq!(payload.len(), 115); let packet = ValmetDnaPacket::try_from(payload).unwrap(); assert_eq!((packet.source_node, packet.destination, packet.length), (0x8028, 0x00ff, 113)); assert_eq!(packet.kind_code, 0x001e_00d0); assert_eq!(packet.kind, Some(MessageKind::Tag)); let ValmetDnaMessage::Tag(tag) = packet.message else { panic!("expected a tag message, got {:?}", packet.message); }; // The tag length is written twice, at offsets 28 and 70; the tag // starts at 72 and ends with the datagram. It is borrowed, not copied. assert_eq!(payload[28..30], [0x00, 0x2b]); assert_eq!(payload[70..72], [0x00, 0x2b]); assert_eq!(tag.tag_length, 43); assert!(std::ptr::eq(tag.tag, &payload[72..])); // The readable form `:e:<class>:<path>`. The anonymization kept the // marker, the class and the delimiters, and substituted the path // letter by letter and digit by digit. assert_eq!(tag.tag_text(), Some(":e:di:AK05:nris05:oigwxj026:oixwge(2):awcrs")); assert_eq!(tag.class(), Some("di")); assert_eq!(tag.path(), Some("AK05:nris05:oigwxj026:oixwge(2):awcrs")); } }
Unknown families
A message whose header is coherent, magic and length, but whose family is neither 0x00000FFF nor 0x001E00D0, decodes with kind: None and message: ValmetDnaMessage::Unknown; its bytes are in body, as they are in every message. The port rule and Decode As accept it, the blind probe does not: off the ports, a magic and a length alone are not enough. The capture has no such message: its 719 AB 01 messages are of the two known families.
Frame 1 with the family 0x00000FFE, on its port and moved (tested):
#![allow(unused)] fn main() { #[test] fn an_unknown_family_is_kept_as_bytes_on_the_ports_only() { let label_of = |frame: &[u8], config: &ParseConfig| { let flow = parse_with(LinkType::ETHERNET, frame, config).unwrap(); flow.application.as_ref().map(|application| application.protocol.label()) }; // Frame 1 with the family 0x00000FFE, which the capture does not show. let mut unknown = hex::decode(STATUS_TELEGRAM_HEX).unwrap(); unknown[DATAGRAM + 11] = 0xfe; let packet = ValmetDnaPacket::try_from(&unknown[DATAGRAM..]).unwrap(); assert_eq!((packet.kind_code, packet.kind), (0x0000_0ffe, None)); assert_eq!(packet.message, ValmetDnaMessage::Unknown); assert_eq!(packet.body, &unknown[DATAGRAM + 12..]); // the body, as is // On UDP 2517 the header is enough; off the ports, the blind probe // refuses a family it does not know, and Decode As accepts it again. let default = ParseConfig::new(); let declared = ParseConfig::new().decode_as(40_001, DecodeAsProtocol::ValmetDna); let mut moved = unknown.clone(); moved[34..38].copy_from_slice(&[0x9c, 0x40, 0x9c, 0x41]); // 40000 -> 40001 assert_eq!(label_of(&unknown, &default), Some("Valmet DNA")); assert_eq!(label_of(&moved, &default), Some("Unknown")); assert_eq!(label_of(&moved, &declared), Some("Valmet DNA")); } }
The beacon
On UDP 4516 → 4517, to the same group, a node sends a 42-byte beacon that carries the same clock. It does not start with AB 01, so ValmetDnaPacket::try_from refuses it (InvalidMagic(0)); TimeBeacon::try_from reads it.
#![allow(unused)] fn main() { #[non_exhaustive] pub struct TimeBeacon { pub code: u16, pub counter: u32, /// The same clock as in the status telegrams. pub clock: Option<DnaClock>, /// The node's IPv4 address: the IP source of the datagram. pub node_ip: Ipv4Addr, } }
| Bytes | Field | Note |
|---|---|---|
| 0–3 | prefix | four zero bytes, checked, not kept |
| 4–5 | magic | AB CC, checked, not kept |
| 6–7 | code | 6 in the capture |
| 8–11 | counter | 0x23800000 in the capture |
| 12–27 | not identified | |
| 28–37 | clock | a DnaClock |
| 38–41 | node_ip | equal to the IP source |
The module documentation gives the beacon a period of 30 s; the twelve seconds of the corpus capture hold a single one, frame 591, sent from the address of node 0x802C, so the period cannot be checked there. With one beacon, the code and the counter are kept as read, without a meaning. The beacon is recognized on UDP 2517, 4516 and 4517 and on a declared port, never blind.
Frame 591 (tested):
#![allow(unused)] fn main() { #[test] fn the_beacon_of_udp_4516_is_not_an_ab01_message() { // Frame 591, UDP 4516 -> 4517: the port rule accepts the beacon. let raw = hex::decode(BEACON_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); assert_eq!(label(&flow), Some("Valmet DNA")); let transport = flow.transport.as_ref().unwrap(); assert_eq!((transport.source_port, transport.destination_port), (Some(4516), Some(4517))); let payload = transport.payload.unwrap(); assert_eq!(payload.len(), 42); // It does not start with AB 01: it is not a message. assert_eq!(ValmetDnaPacket::try_from(payload), Err(ValmetDnaParseError::InvalidMagic(0))); // Four zero bytes and AB CC, then a code and a counter, kept as read: // a single beacon cannot say what they mean. assert_eq!(payload[..6], [0x00, 0x00, 0x00, 0x00, 0xab, 0xcc]); let beacon = TimeBeacon::try_from(payload).unwrap(); assert_eq!((beacon.code, beacon.counter), (6, 0x2380_0000)); // The node address is the IP source, as in a status telegram. assert_eq!(beacon.node_ip, Ipv4Addr::new(10, 0, 2, 9)); assert_eq!(flow.internet.as_ref().unwrap().source, Some(IpAddr::V4(beacon.node_ip))); // The same clock, here 9.9586 s after the rebased start of the capture. let clock = beacon.clock.unwrap(); assert_eq!((clock.second, clock.fraction), (9, 9586)); } }
Validations
All of them are ValmetDnaParseError:
| Error | When |
|---|---|
Truncated { expected, actual } | fewer than the 12 bytes of the header, or a tag message shorter than its 72-byte header |
InvalidMagic(u16) | the first two bytes are not AB 01 |
LengthMismatch { declared, actual } | the declared length plus two is not the size of the datagram |
InvalidMessageLength { kind, expected, actual } | a status telegram of another size than 126 bytes, or a tag message whose header and tag do not make the datagram |
TagLengthMismatch { declared, echo } | the tag lengths at offsets 28 and 70 differ |
InvalidBeaconLength { actual } | a beacon of another size than 42 bytes |
InvalidBeaconPrefix(u32) | the first four bytes of a beacon are not zero |
InvalidBeaconMagic(u16) | the next two are not AB CC |
A clock that is not a date is not an error: it is clock: None. Like every application decoder, a failure is not a corruption: the datagram goes on to the next rules of the table, and nothing goes to corrupted.
Four refusals, and an altered telegram that stays on UDP 2517 and comes out "Unknown" (tested):
#![allow(unused)] fn main() { #[test] fn a_header_or_a_size_out_of_line_is_refused_and_not_a_corruption() { let raw = hex::decode(STATUS_TELEGRAM_HEX).unwrap(); let telegram = &raw[DATAGRAM..]; // One byte less: the declared length, 124, is no longer the // datagram minus two. assert_eq!( ValmetDnaPacket::try_from(&telegram[..125]), Err(ValmetDnaParseError::LengthMismatch { declared: 124, actual: 125 }) ); // The same 125 bytes with a coherent length: the header passes, but // a status telegram is 126 bytes. let mut short = telegram[..125].to_vec(); short[7] = 123; assert_eq!( ValmetDnaPacket::try_from(short.as_slice()), Err(ValmetDnaParseError::InvalidMessageLength { kind: 0x0000_0fff, expected: 126, actual: 125 }) ); // Frame 9 with its two tag lengths at odds, 43 then 42. let tag = hex::decode(TAG_MESSAGE_HEX).unwrap(); let mut echo = tag[DATAGRAM..].to_vec(); echo[71] = 42; assert_eq!( ValmetDnaPacket::try_from(echo.as_slice()), Err(ValmetDnaParseError::TagLengthMismatch { declared: 43, echo: 42 }) ); // Frame 591 cut by one byte: a beacon is 42 bytes. let beacon = hex::decode(BEACON_HEX).unwrap(); assert_eq!( TimeBeacon::try_from(&beacon[DATAGRAM..DATAGRAM + 41]), Err(ValmetDnaParseError::InvalidBeaconLength { actual: 41 }) ); // A refusal is not a corruption. Frame 1 declaring 125 bytes stays on // UDP 2517, goes on to the next rules of the table, and ends "Unknown". let mut altered = raw.clone(); altered[DATAGRAM + 7] = 0x7d; let flow = parse(LinkType::ETHERNET, &altered).unwrap(); assert_eq!(label(&flow), Some("Unknown")); assert!(flow.corrupted.is_none()); let error = ValmetDnaPacket::try_from(&altered[DATAGRAM..]).unwrap_err(); assert_eq!( error.to_string(), "Valmet DNA length 125 does not match the 126 bytes of the datagram" ); } }
Validation without tshark
Without a dissector there is no tshark oracle to compare with. The golden test tests/valmet_dna_golden.rs checks the structure against what the capture carries elsewhere, and against itself over time. Each of the 720 datagrams must be labelled "Valmet DNA" and decode, and:
- every
AB 01message has a length equal to the datagram minus two, a source node0x80NN, the destination0x00FF, and a body of the datagram minus twelve; - every status telegram has 126 bytes, the IP source as
node_ip, the IP destination asmulticast_group, the low byte of its source node asnode_number, one address per node, and a valid clock; from one telegram of a node to the next, the clock advances by 630 to 650 ms,tickby 630 000 to 650 000, andprevious_tickequals the previoustick; - every tag message is 72 bytes plus its tag, the tag starts with
:e:, a readable tag has a non-empty path, and a tag that is not text has ten bytes; - the beacon has the IP source as
node_ip, the code 6, the counter0x23800000, and comes from the address of node0x802C.
The test then freezes the counts: 319 status telegrams, 400 tag messages, 1 beacon; the 17 nodes, with 18 or 19 telegrams each; the classes; the 40 tags that are not text; tags of 10 to 44 bytes, sent by 14 nodes. A second test moves frames 1, 9 and 591 off their ports, as in the detection example. The checks are consistency checks: they tie each named field to the IP header, to the message header or to the node's next telegram, and cannot confirm a field against a reference, since there is none.
In the golden histogram of pcaps_exemple/protocols/ (tests/golden_pcaps.rs), "Valmet DNA" went from 0 to 720 with 11.8.0: the 720 datagrams of the new capture, and no frame of the rest of the corpus, where nothing else moved. The fuzz target parse_valmet_dna runs nightly (data validation), on its input and on mutations of frames 1, 9 and 591: no panic, and when a decode succeeds, the length is the input minus two, the body and the tag are borrowed from the input, the clock is within its ranges, and Application::try_from says "Valmet DNA" exactly when the family is known.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- The bytes not identified stay bytes: 87 of the 126 of the status telegram, 56 of the 72 of the tag message header, 16 of the 42 of the beacon. Those of a message are in
body;TimeBeacondoes not expose its own, which stay in the transport payload. - No meaning is given to the classes of the tags, to the code and the counter of the beacon, or to the families the capture does not show. What a tag message says about its tag, beyond naming it, is not known.
- The destination
0x00FFreads as "all nodes" only because every frame observed carries it and goes to the multicast group; no other value was observed. - The weekday is kept as read, without a convention.
- One site, one capture: the ports, the group and the families are those of one network. On other ports, the blind probe still recognizes the two known families; anything else needs a declared port.
- Read-only: the crate builds no message, rebuilds no control logic, and emits nothing.
WireGuard
WireGuard, the VPN tunnel over UDP, added in 11.6.0 as part of epic #103, in PR #169. Each datagram carries a single message: the initiation or the response of the Noise IK handshake, the cookie that a responder under load sends back, or the encrypted data of the tunnel. The decoder reads the type, the three reserved bytes, the session indexes, the counter of the data and the fixed-size fields (ephemeral keys, encrypted fields, mac1 and mac2), all borrowed from the datagram. Nothing is decrypted: without the keys, the tunnelled packet stays opaque. Module: packet_parser::parse::application::protocols::wireguard; references: J. A. Donenfeld's whitepaper and drivers/net/wireguard/messages.h in Linux.
Detection: three rules, no IANA port
WireGuard has no IANA port. 51820 is the port of the examples of wg(8) and wg-quick(8); without ListenPort, the port is drawn at random, and the corpus shows others: Tailscale on 41641, ProtonVPN on 443, Mullvad on 5060. And a message says little about itself: one type byte from 1 to 4, three reserved bytes, then a fixed size, or for Transport Data a minimum of 32 bytes. The crate therefore has three rules, from the most tolerant to the strictest:
| Where | Probe | Accepts |
|---|---|---|
a port declared with ParseConfig::decode_as(port, DecodeAsProtocol::WireGuard) | ProbeId::WireGuard | the shape of any of the four messages, whatever the reserved bytes |
| UDP 51820 | ProbeId::WireGuardPort | the shape; for a Cookie Reply or Transport Data, zero reserved bytes as well |
| any other UDP port | ProbeId::WireGuardBlind | the shape and zero reserved bytes; for Transport Data, a plausible counter and padding as well |
The shape is what WireGuardPacket::try_from checks: a known type, and the exact size of a handshake or a cookie, or at least 32 bytes of Transport Data. All three probes read the whole datagram, not its first PROBE_CAP bytes. In the table of src/parse/dispatch.rs:
#![allow(unused)] fn main() { // UDP 51820, the port of the examples of wg(8): no IANA port. As in tshark's // heuristic, the shape is enough for an initiation or a response, reserved // bytes included, and a cookie or data have zero reserved bytes. 51820 is an // ephemeral port: after the other port rules (#103). port_rule(ApplicationProtocol::WireGuard, Guard::Udp, is_wireguard_udp_port, ProbeId::WireGuardPort), port_rule(ApplicationProtocol::Ntp, Guard::Udp, is_ntp_udp_port, ProbeId::Ntp), // --- blind cascade --- // ... rule(ApplicationProtocol::Quic, Guard::Udp, ProbeId::QuicLongHeader), // Off 51820: zero reserved bytes, a fixed size or, for data, a counter below // 2^60 and a plaintext padded to sixteen bytes or stopped at the MTU. Last // UDP probe: Transport Data has only `04 00 00 00` and these constraints. rule(ApplicationProtocol::WireGuard, Guard::Udp, ProbeId::WireGuardBlind), rule(ApplicationProtocol::Mqtt, Guard::Tcp, ProbeId::Mqtt), }
Decode As is evaluated before the table (Decode As), and for WireGuard it trusts the caller: the shape is enough, whatever the type and the reserved bytes. It is the one Decode As protocol whose probe is more tolerant than its port rule, on purpose: a declared port is WireGuard on the caller's word, the reserved bytes that Cloudflare uses to spread load included, where 51820 is only an ephemeral port.
On UDP 51820 the rule follows tshark's heuristic. The shape is enough for an initiation or a response, reserved bytes included, but a Cookie Reply or Transport Data must have zero reserved bytes: otherwise a DCE/RPC datagram (04 00 28 00…) or a DNS response whose identifier starts with 0x04 would pass for Transport Data there. It is the last port rule before NTP's, because 51820 falls in the ephemeral port ranges: an ESP, IKE or DNS packet whose peer drew 51820 keeps its label. A unit test of dispatch.rs builds two of them: a 148-byte ESP packet whose SPI starts with 0x01, which has the shape of an initiation, and a 92-byte DNS response whose identifier starts with 0x02, which has the shape of a response.
Elsewhere, the blind probe, the last UDP probe of the cascade, after QUIC, has to make up for a type that is one byte and a Transport Data that has nothing but 04 00 00 00 and its minimum size for it:
- the reserved bytes are zero, for every message: Linux reads the header as one four-byte integer;
- the counter of Transport Data is below 2^60,
REKEY_AFTER_MESSAGES(whitepaper §6.1), the number of messages after which WireGuard starts a new handshake (§6.2): no real counter gets there; - the length of Transport Data is one that padding explains. The plaintext, the message minus its 16-byte header and its 16-byte tag, is padded with zeros to a multiple of 16 (whitepaper §5.4.6), except when that would exceed the MTU: Linux (
calculate_skb_padding) and wireguard-go (calculatePaddingSize) then stop at the MTU. The probe accepts a plaintext that is a multiple of 16, or at least 552 bytes long, the floor of the IPv4 path MTU of Linux (DEFAULT_MIN_PMTU, 512 + 20 + 20). The five 1 452-byte messages of the corpus are of the second kind: 1 420 bytes of plaintext, the MTU ofwg-quick, which is not a multiple of 16.
The probes and REKEY_AFTER_MESSAGES are internal to the crate; the public way to them is parse, parse_with, and classify_payload, which reads the same table: given UDP and no port (None, None), it runs the blind probe alone.
Why so strict: tshark's heuristic, which only requires the type, the size and, for a cookie and data, zero reserved bytes, takes 59 datagrams of Zoom, TeamViewer and League of Legends from nDPI's test corpus for WireGuard. They are Transport Data with zero reserved bytes, which only the counter and the padding rule out; the crate takes none of them. 25 are in the crate's corpus, named as tshark's misfires in the golden test.
The three rules on two real messages and their altered copies (tested); 02 78 00 is what Cloudflare's WARP client puts in the reserved bytes:
#![allow(unused)] fn main() { #[test] fn three_rules_from_the_most_tolerant_to_the_strictest() { let label = |frame: &[u8], config: &ParseConfig| { let flow = parse_with(LinkType::ETHERNET, frame, config).unwrap(); flow.application.as_ref().map(|application| application.protocol.label()) }; // Ethernet and IPv4 without options: the UDP ports are bytes 34-37, // the datagram starts at byte 42. let off_port = |frame: &[u8]| { let mut moved = frame.to_vec(); moved[34..38].copy_from_slice(&[0x9c, 0x40, 0x9c, 0x41]); // 40000 -> 40001 moved }; let reserved = |frame: &[u8]| { let mut altered = frame.to_vec(); altered[43..46].copy_from_slice(&[0x02, 0x78, 0x00]); // non-zero reserved bytes altered }; let default = ParseConfig::new(); let declared = ParseConfig::new().decode_as(40_001, DecodeAsProtocol::WireGuard); let keepalive = hex::decode(WG_KEEPALIVE_HEX).unwrap(); let initiation = hex::decode(WG_INITIATION_HEX).unwrap(); // As captured, on 51820, then moved to 40000 -> 40001: the port rule, // then the blind probe. assert_eq!(label(&keepalive, &default), Some("WireGuard")); assert_eq!(label(&off_port(&keepalive), &default), Some("WireGuard")); // Non-zero reserved bytes: 51820 still takes a handshake, but not // Transport Data, like tshark's heuristic. assert_eq!(label(&reserved(&initiation), &default), Some("WireGuard")); assert_eq!(label(&reserved(&keepalive), &default), Some("Unknown")); // The blind probe takes neither... assert_eq!(label(&off_port(&reserved(&initiation)), &default), Some("Unknown")); assert_eq!(label(&off_port(&reserved(&keepalive)), &default), Some("Unknown")); // ... and a declared port takes both: Decode As checks the shape only. assert_eq!(label(&off_port(&reserved(&initiation)), &declared), Some("WireGuard")); assert_eq!(label(&off_port(&reserved(&keepalive)), &declared), Some("WireGuard")); } }
The blind probe on real traffic: a ProtonVPN keepalive on UDP 443, and a Zoom datagram that tshark's heuristic accepts (tested):
#![allow(unused)] fn main() { #[test] fn the_blind_probe_on_real_traffic() { // ProtonVPN on UDP 443: the QUIC short-header rule of that port wants // the 0x40 bit in the first byte, which no WireGuard type has, and the // blind probe, last of the UDP cascade, takes the keepalive. let frame = hex::decode(PROTONVPN_KEEPALIVE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &frame).unwrap(); assert_eq!(flow.transport.as_ref().unwrap().destination_port, Some(443)); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "WireGuard"); // Zoom: `04 00 00 00` and 81 bytes are the shape of Transport Data, and // tshark's heuristic accepts the datagram. The blind probe does not. let frame = hex::decode(ZOOM_DATAGRAM_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &frame).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "Unknown"); let datagram = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = WireGuardPacket::try_from(datagram).unwrap(); // the shape is there assert_eq!(packet.reserved, [0; 3]); let WireGuardMessage::TransportData(data) = &packet.message else { panic!("expected the shape of Transport Data, got {:?}", packet.message); }; assert!(data.counter >= 1 << 60); // REKEY_AFTER_MESSAGES let plaintext = datagram.len() - 32; // minus the header and the tag assert_eq!(plaintext, 49); // not a multiple of 16, and below 552 // A port the caller declares is WireGuard as soon as the shape is. let config = ParseConfig::new().decode_as(8801, DecodeAsProtocol::WireGuard); let flow = parse_with(LinkType::ETHERNET, &frame, &config).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "WireGuard"); } }
The message
#![allow(unused)] fn main() { pub struct WireGuardPacket<'a> { /// 1 to 4. pub message_type: u8, /// Zero in the protocol; Cloudflare uses them to spread load. pub reserved: [u8; 3], pub message: WireGuardMessage<'a>, } pub enum WireGuardMessage<'a> { HandshakeInitiation(HandshakeInitiation<'a>), HandshakeResponse(HandshakeResponse<'a>), CookieReply(CookieReply<'a>), TransportData(TransportData<'a>), } pub struct HandshakeInitiation<'a> { /// The index the initiator picks for the session. pub sender_index: u32, /// Curve25519 ephemeral public key. pub unencrypted_ephemeral: &'a [u8; 32], /// The initiator's static public key, encrypted. pub encrypted_static: &'a [u8; 48], /// TAI64N timestamp, encrypted (anti-replay). pub encrypted_timestamp: &'a [u8; 28], pub mac1: &'a [u8; 16], /// Zero unless after a Cookie Reply. pub mac2: &'a [u8; 16], } pub struct HandshakeResponse<'a> { /// The index the responder picks for the session. pub sender_index: u32, /// The index of the initiation it answers. pub receiver_index: u32, pub unencrypted_ephemeral: &'a [u8; 32], /// A Poly1305 tag over an empty plaintext. pub encrypted_nothing: &'a [u8; 16], pub mac1: &'a [u8; 16], pub mac2: &'a [u8; 16], } pub struct CookieReply<'a> { pub receiver_index: u32, /// XChaCha20-Poly1305 nonce. pub nonce: &'a [u8; 24], pub encrypted_cookie: &'a [u8; 32], } pub struct TransportData<'a> { /// The session index of the receiver. pub receiver_index: u32, /// Message counter, also the ChaCha20-Poly1305 nonce. pub counter: u64, /// The encrypted packet, its 16-byte tag included. pub encrypted_packet: &'a [u8], } }
All of them are #[non_exhaustive], and a match on WireGuardMessage needs a _ arm. TransportData::is_keepalive() is true when the encrypted packet is the tag alone, a 32-byte message.
Every message starts with the same four-byte header, and every integer is little-endian:
| Bytes | Field |
|---|---|
| 0 | message_type, 1 to 4 |
| 1–3 | reserved |
What follows depends on the type, with a fixed size for three of them:
| Type | WireGuardMessage | Size | Fields (offset in the message, size) |
|---|---|---|---|
| 1 | HandshakeInitiation | 148 | 4 sender_index, 8 unencrypted_ephemeral (32), 40 encrypted_static (48), 88 encrypted_timestamp (28), 116 mac1 (16), 132 mac2 (16) |
| 2 | HandshakeResponse | 92 | 4 sender_index, 8 receiver_index, 12 unencrypted_ephemeral (32), 44 encrypted_nothing (16), 60 mac1 (16), 76 mac2 (16) |
| 3 | CookieReply | 64 | 4 receiver_index, 8 nonce (24), 32 encrypted_cookie (32) |
| 4 | TransportData | 32 or more | 4 receiver_index, 8 counter (8), 16 encrypted_packet, to the end of the datagram |
The first handshake of wireshark_wireguard-ping-tcp.pcap, between two Linux network namespaces (tested):
#![allow(unused)] fn main() { #[test] fn a_wireguard_handshake_on_udp_51820() { let initiation_frame = hex::decode(WG_INITIATION_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &initiation_frame).unwrap(); assert_eq!(flow.transport.as_ref().unwrap().destination_port, Some(51820)); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "WireGuard"); let datagram = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = WireGuardPacket::try_from(datagram).unwrap(); assert_eq!((packet.message_type, packet.reserved), (1, [0; 3])); let WireGuardMessage::HandshakeInitiation(initiation) = &packet.message else { panic!("expected an initiation, got {:?}", packet.message); }; assert_eq!(datagram.len(), 148); assert_eq!(initiation.sender_index, 0x30d0_37d8); // Fixed-size fields, borrowed from the datagram. assert_eq!(initiation.unencrypted_ephemeral.as_slice(), &datagram[8..40]); assert_eq!(initiation.mac1.as_slice(), &datagram[116..132]); assert_eq!(initiation.mac2, &[0; 16]); // no Cookie Reply came before // The response answers that index with one of its own. let response_frame = hex::decode(WG_RESPONSE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &response_frame).unwrap(); let datagram = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = WireGuardPacket::try_from(datagram).unwrap(); let WireGuardMessage::HandshakeResponse(response) = &packet.message else { panic!("expected a response, got {:?}", packet.message); }; assert_eq!(datagram.len(), 92); assert_eq!(response.sender_index, 0xab7d_f406); assert_eq!(response.receiver_index, initiation.sender_index); assert_eq!(response.encrypted_nothing.as_slice(), &datagram[44..60]); } }
and the first data of the same session, then a keepalive (tested):
#![allow(unused)] fn main() { #[test] fn transport_data_and_a_keepalive() { let frame = hex::decode(WG_DATA_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &frame).unwrap(); assert_eq!(flow.application.as_ref().unwrap().protocol.label(), "WireGuard"); let datagram = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = WireGuardPacket::try_from(datagram).unwrap(); let WireGuardMessage::TransportData(data) = &packet.message else { panic!("expected Transport Data, got {:?}", packet.message); }; assert_eq!(data.receiver_index, 0xab7d_f406); // the responder's index assert_eq!(data.counter, 0); assert_eq!(datagram.len(), 128); // 96 bytes of plaintext, a multiple of 16, then the 16-byte tag. assert_eq!(data.encrypted_packet.len(), 112); assert!(!data.is_keepalive()); let frame = hex::decode(WG_KEEPALIVE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &frame).unwrap(); let datagram = flow.transport.as_ref().unwrap().payload.unwrap(); let packet = WireGuardPacket::try_from(datagram).unwrap(); let WireGuardMessage::TransportData(keepalive) = &packet.message else { panic!("expected Transport Data, got {:?}", packet.message); }; assert_eq!(keepalive.counter, 3); assert_eq!(keepalive.encrypted_packet.len(), 16); // the tag alone assert!(keepalive.is_keepalive()); } }
Validations
All of them are WireGuardParseError, in packet_parser::errors::application::wireguard:
| Error | When |
|---|---|
Truncated { expected, actual } | fewer than 4 bytes, or Transport Data shorter than 32 |
UnknownMessageType(u8) | a type other than 1 to 4, among them 0xC1 to 0xC4 of Cloudflare's WARP client |
InvalidLength { message_type, expected, actual } | an initiation, a response or a cookie that is not exactly 148, 92 or 64 bytes |
These errors never reach corrupted: a datagram the probes refuse goes on down the table, and usually comes out "Unknown". On real bytes (tested):
#![allow(unused)] fn main() { #[test] fn what_wireguard_packet_refuses() { let frame = hex::decode(WG_KEEPALIVE_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &frame).unwrap(); let keepalive = flow.transport.as_ref().unwrap().payload.unwrap(); assert_eq!( WireGuardPacket::try_from(&keepalive[..31]), Err(WireGuardParseError::Truncated { expected: 32, actual: 31 }) ); let frame = hex::decode(WG_INITIATION_HEX).unwrap(); let flow = parse(LinkType::ETHERNET, &frame).unwrap(); let mut longer = flow.transport.as_ref().unwrap().payload.unwrap().to_vec(); longer.push(0); assert_eq!( WireGuardPacket::try_from(longer.as_slice()), Err(WireGuardParseError::InvalidLength { message_type: 1, expected: 148, actual: 149 }) ); // The type byte of Cloudflare's official WARP client. let mut warp = keepalive.to_vec(); warp[0] = 0xc4; let error = WireGuardPacket::try_from(warp.as_slice()).unwrap_err(); assert_eq!(error, WireGuardParseError::UnknownMessageType(0xc4)); assert_eq!(error.to_string(), "Unknown WireGuard message type 196"); } }
Oracle: 128 messages, field by field
tests/wireguard_golden.rs runs the nine captures of pcaps_exemple/protocols/wireguard/ and compares every message with tshark 4.6.6, which registers WireGuard on no port: tools/wireguard_oracle.sh enables the wg heuristic, follows the conversations it pins after a Handshake Initiation, uses an empty Wireshark profile and no key, and freezes in tests/data/wireguard_tshark_oracle.tsv the ports, length, type, reserved bytes, indexes, counter, ephemeral key, mac1, mac2, nonce, cookie and keepalive flag of each message. Of the 153 messages tshark sees, the crate labels and decodes the same 128, field for field: 6 initiations, 6 responses and 116 Transport Data, 5 of them keepalives and 5 of them the 1 452-byte messages stopped at the MTU; no capture carries a Cookie Reply. The other 25 are named, not hidden: the Zoom and League of Legends datagrams that tshark accepts and the blind probe refuses.
| Capture | Messages | Implementation | Server port | Origin |
|---|---|---|---|---|
wireshark_wireguard-ping-tcp.pcap | 22 | Linux, two network namespaces: two handshakes, 18 Transport Data | 51820 | Wireshark repository |
wireshark_wireguard-psk.pcap | 4 | the same bench with a pre-shared key: two handshakes | 51820 | Wireshark repository |
ndpi_nordvpn.pcap | 22 | NordVPN (NordLynx) on Windows | 51820 | nDPI test corpus |
ndpi_tunnelbear.pcap | 10 | TunnelBear, Transport Data | 51820 | nDPI test corpus |
corelight_tailscale_linux.pcap | 46 | Tailscale (wireguard-go) on Linux, Transport Data | 41641 | Corelight |
ndpi_protonvpn.pcap | 14 | ProtonVPN: a handshake and Transport Data | 443 | nDPI test corpus |
ndpi_mullvad_wireguard.pcap | 10 | Mullvad, Transport Data | 5060 | nDPI test corpus |
ndpi_zoom2.pcap | 0 | Zoom: 22 datagrams tshark takes for WireGuard | — | nDPI test corpus |
ndpi_lol_wild_rift_udp.pcap | 0 | League of Legends: Wild Rift: 3 such datagrams | — | nDPI test corpus |
The golden test checks the other side too. None of the neighbours of these messages comes out WireGuard:
- the 61 "disco" messages of Tailscale on the same port 41641;
- the two extended handshakes of TunnelBear, 204 and 100 bytes;
- the 43 obfuscated OpenVPN datagrams of NordVPN on UDP 1198;
- frame 41 of ProtonVPN, retouched by hand in nDPI's corpus.
It then replays the 128 messages off their port, from UDP 40000 to 40001, where the blind probe recognizes all of them. With 02 78 00 in their reserved bytes, the outcome depends on the route:
| Route | Messages kept, of 128 |
|---|---|
| the blind probe | none |
| port 51820 | the 12 handshakes |
| a port declared by Decode As | all 128 |
No real capture carries WireGuard over IPv6: the keepalive of frame 9 of wireshark_wireguard-ping-tcp.pcap, put in a raw IPv6 frame, follows the same rules. In the golden histogram of the whole corpus, "WireGuard" counts these 128 frames.
The fuzz target parse_wireguard runs nightly. It must not panic, and on success the size is the one of the type, every borrowed field points into the input, a keepalive is exactly 32 bytes, and what the blind cascade labels WireGuard has zero reserved bytes.
What is left out
The limits every protocol shares, reassembly and checksums among them, are on the Limits page. The ones below are this protocol's own.
- Decryption: there are no keys, so the encrypted fields and
encrypted_packetstay opaque,mac1andmac2are not checked, and there is no inner flow: the tunnelled packets are not peeled like the encapsulations of the tunnels chapter. - Cookie Reply has no real capture: it is decoded at the offsets of the whitepaper, and a synthetic unit test covers it.
- boringtun (Cloudflare) and its derivatives (NordSecurity neptun, Firezone) do not pad their data ("spec requires padding to 16 bytes, but actually works fine without it",
noise/session.rs): off 51820 and the declared ports, only their handshakes, their keepalives and their packets whose size happens to fit are recognized. - A tunnel MTU below 552 and not a multiple of 16: the packets whose padding stops at that MTU are recognized only on 51820 or by Decode As.
- Cloudflare's official WARP client also changes the type byte,
0xC1to0xC4: it is not decoded, even by Decode As, which still requires a known type. - No session state: indexes and counters are values. Nothing ties a response to its initiation or checks that a counter grows; one datagram at a time, like the rest of the crate.
Protocols
The crate gives a flow one of 60 labels, the variants of ApplicationProtocol::ALL. This page lists them all, with the route that leads to each one and the page that describes it. The protocols decoded below the application layer, which get no label, come after.
The 60 labels
The route is how the dispatch reaches the label. A port rule asks for a port and a content that agree; a blind rule asks for the content alone, on any port; a terminal port rule ends the dispatch when the content does not match. The Application chapter explains the three, and the Glossary defines each word. A tunnel label is given to the outer flow of an encapsulation.
A label written with "then" has a port rule and a blind rule: the port rule is tried first, and is often the more lenient of the two. One label, RTP, has no rule at all: it is given on a port the caller declares, and the RTP page says why.
| Label | Route | Transport and ports | Described in | tshark oracle | Since |
|---|---|---|---|---|---|
AMS | port | TCP 48898, UDP 48899 | rules 21, 22 of the Application | none | 5.0.0 or earlier |
ASTERIX | blind | UDP | ASTERIX | 44 411 frames, record by record | 11.3.0 |
BACnet/IP | port and blind | UDP 47808 to 47823, then any UDP port | BACnet/IP | 45 datagrams | 11.6.0 |
Bitcoin | blind | TCP | rule 54 of the Application | none | 5.0.0 or earlier |
CAPWAP | tunnel, then port | UDP 5247 for the tunnel, then UDP 5246 and 5247 for what it does not peel | Tunnels | 341 datagrams | 5.0.0 or earlier |
COTP | port | TCP 102 | rule 7 of the Application | none | 5.0.0 or earlier |
DCE/RPC | blind | TCP | DCE/RPC | 385 segments | 13.3.0 |
DHCP | port and blind | UDP 67, 68, then any UDP port | rules 3, 68 of the Application | none | 5.0.0 or earlier |
DHCPv6 | port | UDP 546, 547 | rule 2 of the Application | none | 5.0.0 or earlier |
DIS | port and blind | UDP 3000, then any UDP port | DIS | 393 frames | 11.6.0 |
DNP3 | blind | TCP and UDP | DNP3 | 218 frames | 11.6.0 |
DNS | port and blind | TCP 53, UDP 53, then any UDP port | DNS, mDNS and LLMNR | counts and digests | 5.0.0 or earlier |
ESP | port | UDP 4500 | ESP | 323 packets, 315 of them in UDP | 11.6.0 |
EtherNet/IP | blind | TCP and UDP | rules 56, 57 of the Application | none | 5.0.0 or earlier |
FTP | port and blind | TCP 21, then any TCP port but 25, 587, 119 | rules 8, 11 of the Application | none | 9.0.0 |
Geneve | tunnel | UDP 6081 | Tunnels | none | 10.5.0 |
GIOP | blind | TCP | GIOP | 135 messages | 5.0.0 or earlier |
GRE | tunnel | IP protocol 47 | Tunnels | none | 10.4.0 |
GTP-U | tunnel | UDP 2152 | Tunnels | none | 11.2.0 |
HTTP | blind | TCP | HTTP | 298 frames | 5.0.0 or earlier |
IEC 104 | port | TCP 2404 | IEC 60870-5-104 | 373 segments | 11.6.0 |
IKE | port | UDP 500, 4500 | IKE | 535 messages | 11.6.0 |
IP-in-IP | tunnel | IP protocols 4 and 41 | Tunnels | none | 10.4.0 |
Java RMI | port and blind | TCP 1099, then any TCP port | Java RMI | 236 segments | 13.0.0 |
LLMNR | port, terminal | UDP 5355 | DNS, mDNS and LLMNR | none | 10.4.0 |
mDNS | port, terminal | UDP 5353 | DNS, mDNS and LLMNR | none | 9.0.0 |
ModbusTCP | port and blind | TCP 502, then any TCP port | Modbus/TCP and UMAS | 601 segments, with UMAS | 5.0.0 or earlier |
ModbusUDP | port | UDP 502 | Modbus over UDP | 38 datagrams | 12.0.0 |
MQTT | blind | TCP | rule 78 of the Application | none | 5.0.0 or earlier |
NAT-keepalive | port | UDP 4500 | ESP | none | 11.6.0 |
NBNS | port | UDP 137 | rule 17 of the Application | none | 10.4.0 |
NBSS | port | TCP 139, 445 | rule 18 of the Application | none | 10.4.0 |
NMF | blind | TCP | NMF | 23 segments | 13.3.0 |
NNTP | port and blind | TCP 119, then any TCP port but 21, 25, 587 | rules 10, 13 of the Application | none | 9.0.0 |
NTP | port and blind | UDP 123, then any UDP port | NTP | 1 308 datagrams | 5.0.0 or earlier |
OPC UA | port and blind | TCP 4840, 12001, then any TCP port | rules 25, 55 of the Application | none | 5.0.0 or earlier |
OpenVPN | port | UDP 1194, TCP 1194 | rules 19, 20 of the Application | none | 10.4.0 |
PostgreSQL | port and blind | TCP 5432, then any TCP port | PostgreSQL | 276 segments | 5.0.0 or earlier |
PTP | port | UDP 319, 320 | PTP | 3 328 messages, Ethernet and UDP | 11.5.0 |
QUIC | port and blind | UDP 443 (short header, and the long header of any version), then any UDP port (long header of QUIC v1) | rules 23, 24, 72 of the Application | none | 5.0.0 or earlier |
RADIUS | port and blind | UDP 1812, 1813, 1645, 1646, 3799, then any UDP port | RADIUS | 95 packets | 11.6.0 |
RDP | port | TCP 3389 | RDP | 861 segments | 11.6.0 |
RTCP | blind | UDP | RTCP | 52 datagrams | 13.3.0 |
RTP | declared port only | UDP, on a port declared with Decode As | RTP | 15 011 frames | 13.3.0 |
RTPS | blind | UDP | RTPS | 231 frames | 11.6.0 |
S7Comm | blind | TCP | rule 6 of the Application | counts and digests | 5.0.0 or earlier |
SIP | blind | TCP and UDP, any port | SIP | 201 frames | 13.2.0 |
SMTP | port and blind | TCP 25, 587, then any TCP port but 21, 119 | rules 9, 12 of the Application | none | 9.0.0 |
SNMP | port and blind | UDP 161, 162, then any TCP or UDP port | rules 1, 60 of the Application | none | 5.0.0 or earlier |
SRVLOC | port and blind | TCP 427, UDP 427, then any TCP or UDP port | rules 4, 5, 69 of the Application | none | 5.0.0 or earlier |
SSDP | port | UDP 1900 | rule 16 of the Application | none | 10.4.0 |
SSH | blind | TCP | rules 62, 65 of the Application | none | 10.1.0 |
STANAG 5066 | port | TCP 5066 | STANAG 5066 SIS | 34 segments | 11.6.0 |
STP | link layer | no transport | STP | none | 10.4.0 |
TLS | blind | TCP | TLS | counts and digests | 5.0.0 or earlier |
UMAS | port and blind | TCP 502, then any TCP port | Modbus/TCP and UMAS | 601 segments, with ModbusTCP | 11.1.0 |
Unknown | no rule matched | any | Application | not a protocol | 5.0.0 or earlier |
Valmet DNA | port and blind | UDP 2517, 4516, 4517, then any UDP port | Valmet DNA | none: tshark has no dissector | 11.8.0 |
VXLAN | tunnel | UDP 4789 | Tunnels | none | 10.5.0 |
WireGuard | port and blind | UDP 51820, then any UDP port | WireGuard | 128 messages | 11.6.0 |
Three columns need a word.
- Described in. A label without a page of its own points to its rows in the dispatch table.
- tshark oracle. The number of frames, segments or messages that a golden test of the crate compares with tshark field by field. "Counts and digests" is weaker:
tests/tshark_regression.rsandtests/s7comm_regression.rscompare the set of frames that carry the label, not their fields. "None" means no comparison with tshark; the label is still counted, over the whole corpus, by the golden histogram oftests/golden_pcaps.rs. - Since. The first tagged release whose dispatch gives the label. The tags of the repository start at 5.0.0, so "5.0.0 or earlier" is as far back as they tell.
The caller can declare extra ports for the protocols of Decode As.
Decoded without a label
These protocols sit below the application layer. The crate decodes them into a link, internet or transport layer, and PacketFlow::application stays None.
| Protocol | Where it is found | Layer | Described in | tshark oracle |
|---|---|---|---|---|
| PTP over Ethernet | EtherType 0x88F7 | internet | PTP | 3 328 messages, Ethernet and UDP |
| GOOSE | EtherType 0x88B8 | internet | GOOSE | 494 frames |
| LLDP | EtherType 0x88CC | internet | LLDP | 276 frames |
| Profinet | EtherType 0x8892 | internet | Profinet | 232 frames |
| ARP | EtherType 0x0806 | internet | ARP | none |
| ESP, native | IP protocol 50 | transport | ESP | 323 packets, 8 of them native |
| ICMPv4 and ICMPv6 | IP protocols 1 and 58 | transport | ICMPv4 and ICMPv6 | none |
STP is the exception: it has no internet layer either, and the pipeline labels it "STP" from the link layer (STP).
Tunnels
A tunnel is decoded twice: the outer flow takes the tunnel's label, and the conversation it carries is a second PacketFlow in inner. The Tunnels chapter has the details.
| Label | Detected from | Carries |
|---|---|---|
GRE | IP protocol 47 | IPv4, IPv6 or Ethernet |
IP-in-IP | IP protocols 4 and 41 | a bare IP packet |
CAPWAP | UDP 5247 | IEEE 802.11, then LLC/SNAP; since 13.3.0 the label without inner for the rest, on UDP 5246 and 5247 |
VXLAN | UDP 4789 | a full Ethernet frame |
Geneve | UDP 6081 | Ethernet or bare IP |
GTP-U | UDP 2152 | a bare IP packet |
Link formats
The link layer is chosen by the caller, from the link type of the capture. Each format has its page: Ethernet, with PPPoE session (6 795 session frames against tshark) and IEEE 802.3br inside it, Linux cooked capture, RAW IP and BSD loopback.
Tunnels
Some packets carry a whole other packet inside their payload. The base pipeline is layered and single-level: without help it only sees the outer flow (say, UDP between two data centres) and misses the real conversation nested inside.
inner and flatten()
When a tunnel is recognized, its name goes into the outer flow's Application::protocol, its headers are peeled, and the encapsulated packet is fed back into the same L3/L4/L7 pipeline, recursively, into inner:
#![allow(unused)] fn main() { pub struct PacketFlow<'a> { // ... pub inner: Option<Box<PacketFlow<'a>>>, } }
One wire packet then yields several flow levels, outermost first:
#![allow(unused)] fn main() { let flow = parse(LinkType::ETHERNET, &packet)?; for level in flow.flatten() { println!("{:?} -> {:?}", level.internet, level.transport); } }
Here is the TCP SYN of the previous chapters, carried in a VXLAN tunnel between two hypervisors:
The outer flow stops at the VXLAN header: its application is the tunnel's name, and the 74 bytes that follow, a complete Ethernet frame, are parsed again from the link layer up into inner. flatten() returns the two levels, outer first.
A non-tunneled packet yields one entry. The inner flows borrow the same buffer as the outer one: peeling is zero-copy, only the recursion boxes.
Nesting is bounded by MAX_TUNNEL_DEPTH = 4, an anti-loop guard against malformed traffic that could claim endless encapsulation. The bound counts flow levels, the outer one included: flatten() returns at most four entries. At the fourth level the tunnel is no longer peeled, and its payload goes to the dispatch table like any other: four VXLAN layers around the SYN above give three flows labelled "VXLAN", then a fourth labelled "Unknown", and the SYN is never read.
Supported tunnels
| Tunnel | Detected from | Inner |
|---|---|---|
| CAPWAP-Data (RFC 5415) | UDP/5247 | IEEE 802.11 → LLC/SNAP → L3 |
| GRE v0 (RFC 2784/2890) | IP protocol 47 | IPv4, IPv6 or Ethernet (0x6558) |
| IP-in-IP | IP protocols 4 and 41 | bare IPv4 / IPv6 |
| VXLAN (RFC 7348) | UDP/4789 | full Ethernet frame |
| Geneve (RFC 8926) | UDP/6081 | Ethernet (0x6558) or bare IP, options skipped |
| GTP-U (3GPP TS 29.281) | UDP/2152 | bare IP, no L2 |
CAPWAP without an inner flow
Only a CAPWAP data frame, an IEEE 802.11 data frame on UDP 5247, carries a conversation to peel. Until 13.3.0 everything else on the two CAPWAP ports was "Unknown": the control channel on UDP 5246, in clear or under DTLS, the keep-alives of the data channel, fragments, and 802.11 management frames. Since 13.3.0 (#355, PR #360) they are labelled "CAPWAP", with no inner.
The label comes from rule 74 of the dispatch table, a port rule on UDP 5246 and 5247. Its probe accepts two shapes:
- a CAPWAP header (RFC 5415 §4.3): version 0, a header length of at least two words that fits in the datagram, a wireless binding identifier that is not zero, reserved bits that are null, and neither the last-fragment bit nor a fragment offset without the fragment bit;
- the DTLS preamble, followed by a DTLS 1.0 or 1.2 record. What the record carries is encrypted, and is not read.
The rule sits in the blind cascade, after every UDP probe that has a signature. 5246 and 5247 are above 1023, and any client may draw them as its source port: a DNS answer or a QUIC packet that lands there keeps its own label. The same datagram on another port is "Unknown": the header alone is too loose to run blind.
The golden test tests/capwap_golden.rs compares the crate with tshark 4.6.9 on 341 datagrams of four captures already in the corpus (tools/capwap_oracle.sh, frozen in tests/data/capwap_tshark_oracle.tsv): 34 control messages in clear, 284 under DTLS, 12 keep-alives and 11 management frames. The crate and tshark name the same datagrams, and none of them has an inner.
Encrypted encapsulations
The encrypted encapsulations get a label but no inner: OpenVPN, WireGuard and ESP in UDP 4500 carry ciphertext, and native ESP, IP protocol 50, is a transport layer without a payload. A PPPoE session is not a tunnel either: the link layer peels it like a VLAN tag, and the IP packet it carries is the flow itself.
Two detection points
Tunnels are looked for at two places in the pipeline, because they live at two levels:
- IP-level (
detect_inner_l3), fromInternet::payload_protocol, first in the L7 stage, before the transport-level detection and the application probes. Transport parsing has already run by then, but GRE and IP-in-IP have no transport layer, so their detection does not depend on the hollowTransportthe catch-all branch oftry_from_partsbuilds for them. A fragmented packet has nopayload_protocol, so a tunnel carried in fragments is not peeled. For IP-in-IP, the outer protocol number announces the inner version (4 or 41), and the raw-IP decoder checks it against the inner version nibble: a mismatch is refused. - Transport-level (
detect_inner), from a UDP port and the payload shape: CAPWAP, VXLAN, Geneve, GTP-U.
Detection returns None, never an error: no tunnel, an encrypted payload (CAPWAP over DTLS), a truncated one, or a shape the crate does not decode all mean "this is just an ordinary flow". The flow then goes to the dispatch table, which may still name it: that is how a CAPWAP datagram without a conversation to peel gets its label.
Refuse, don't guess
Every tunnel decoder rejects the variants it cannot attest instead of guessing a shape: GRE version 1 (PPTP), ERSPAN and routing bits; VXLAN GBP/GPE flag extensions; Geneve OAM control messages; GTPv0, GTP' (a billing protocol on the same port) and every GTP-U message type other than G-PDU (echo requests and the whole control plane carry no user packet).
GTP-U is special in one way: alone among these, its header says nothing about what it carries (VXLAN is always Ethernet, Geneve announces an EtherType). So it is the only tunnel whose label requires the inner packet to parse cleanly first.
A fragmented outer datagram is never peeled: reassembly is stateful, and a tunnel must not be reported as more complete than the datagram carrying it.
The inner link layer is honest
The inner packet enters the pipeline through the same DecodedLink as a top-level packet: VXLAN produces an Ethernet link layer; GRE and Geneve an Ethernet one when they announce 0x6558, a RawIp one for bare IP; IP-in-IP and GTP-U a RawIp one; and CAPWAP an Ieee80211Link with the real 802.11 addresses and the SNAP protocol. Nothing fabricates an Ethernet header for a tunnel that does not carry one, which is the same principle as the data link chapter.
The "Decode As" configuration is propagated into the inner flows, so a declared port works inside a tunnel too.
Limits
parse is stateless: it reads one packet, keeps nothing, and knows nothing of the packets before it. Most of the limits of the crate follow from that choice. This page lists them once, with what each one costs a consumer and what the crate exposes to detect it. The limits of a single protocol are in the "What is left out" section of its page.
What a stateless parser cannot see
| Limit | What follows for a consumer | What the crate exposes | With a stateful layer |
|---|---|---|---|
| No TCP reassembly | A message cut by segmentation is read as far as its first segment goes. The segments that carry the rest start in the middle of a message and are "Unknown". | truncated on the last unit of a segment, for the decoders that tile it: GIOP, RDP, IEC 104, STANAG 5066 | Reassemble each direction of a flow, then probe |
| A record over several segments | A TLS record that runs into the next segment makes the following segments "Unknown": they start with ciphertext, not with a record header. | Nothing | The same reassembly |
| One label per packet, no memory of the flow | A flow can carry several labels: "Unknown" for its continuation segments, "TLS" after a STARTTLS or an RDP negotiation. SSH is recognized by its identification string alone, one segment in each direction. | The flow identity, which stays the same: the consumer can keep the first label that is not "Unknown" | Pin the label of a flow, and decide when a protocol switch may change it |
| Retransmissions are parsed again | A retransmitted segment gets the label of the segment it repeats, and is counted twice. The HTTP oracle sets 6 such segments aside, the RDP oracle 10. | The TCP sequence number, in TransportDetails | Compare sequence numbers per flow |
| No IP reassembly | A fragmented datagram has no transport layer, no ports and no label, its first fragment included. | Ipv4Packet::is_fragmented(), Ipv6Packet::is_fragmented() | Reassemble, then parse the transport layer |
| A fragmented tunnel is not peeled | The outer flow has no inner: the conversation inside the tunnel is not seen. | is_fragmented() on the outer packet | The same reassembly |
| A reply is not paired with its request | Nothing matches a response to a request, by transaction identifier or otherwise. A reply that is one byte long, like PostgreSQL's answer to an SSLRequest, is recognized on its port only. | The identifiers each decoder reads | Keep the pending requests of a flow |
| A header that is opaque without the handshake | A QUIC short header is plausible on UDP 443 and undecidable elsewhere: off that port, the datagrams of an established connection are "Unknown". | Decode As, QuicShortHeader | Remember the connection IDs of the handshake |
| A header too weak to prove anything alone | An RTP packet has two fixed bits. parse never names it by its content: it is "Unknown" off a declared port. | Decode As, Rtp, and the SSRC and sequence number that RtpPacket::try_from reads (RTP) | Confirm a flow by several packets with one SSRC and sequence numbers that follow each other |
| Preempted frames | An IEEE 802.3br fragment of a preemptible frame is refused. | Err, with LinkLayerError::PreemptibleFragment | Reassemble the mPackets |
What the crate chooses not to do
| Limit | What follows for a consumer | What the crate exposes |
|---|---|---|
| Checksums are never verified during a parse | A packet damaged in transit parses like a healthy one. The choice is deliberate: on a sender-side capture with hardware offloading the checksums are not computed yet. | packet_parser::checksum::verify_ipv4_header_checksum, verify_tcp_checksum, verify_udp_checksum |
| Nothing is decrypted | TLS, SSH, ESP, WireGuard, OpenVPN and QUIC are labelled from their cleartext envelope. What they carry is not seen: HTTP inside TLS is "TLS". | The label of the envelope |
| The application layer is a label | parse names the protocol and decodes nothing above the transport layer. | The decoder of each protocol, called on the transport payload: XxxPacket::try_from |
| Tunnels are peeled four levels deep | At MAX_TUNNEL_DEPTH, the fourth level, a tunnel is no longer peeled and its payload stays opaque. | flatten(), which returns at most four flows |
| The text probes read a prefix | The FTP, SMTP, NNTP and HTTP probes validate the first PROBE_CAP bytes of a payload, 18 KiB, and nothing beyond. | The decoder, which reads the whole payload when called directly |
| A truncated capture is not told apart | parse receives the captured bytes only. A packet cut by the snapshot length fails its length checks and is reported like a packet with a lying header. | corrupted, with the layer and the typed error |
A protocol the crate does not decode is "Unknown" | A proprietary or in-house protocol over TCP or UDP gets no name. | Since 13.0.0, a parser added by the caller, and since 13.1.0 a rule file, name it after the table (Custom parsers and rules) |
Three fields to look at
corruptedisSomewhen a layer was announced and its bytes were refused. The layers below it are valid; the layers above it are absent, not empty (Getting started).is_fragmented()explains a flow with an internet layer and no transport (IPv4).truncatedmarks a message whose end is in a later segment. It is on the decoded structs, not onPacketFlow.
A layer that is None with corrupted also None is neither an error nor a limit: the crate has no decoder for that protocol.
Adding a new protocol
The crate is built so that adding a protocol is a mechanical job with the same shape every time. The reference document in the repository is METHODE_AJOUT_PROTOCOLE.md (in French); this chapter is its summary.
Mandatory principles
- The parser implements
TryFrom<&[u8]>, as a linear sequence: length pre-check, oneextract_*per constrained field in wire order, cross-field validations, then construction. The canonical model isntp.rs. - Zero-copy:
&'a [u8]for payloads and variable fields, scalars for fixed fields,from_be_bytesfor numbers. NoVec,String,to_vec()orclone()in a parsing struct. A&'a stronly when the protocol mandates UTF-8 and it was validated. - Any pre-allocation sized by a field of the packet goes through
bounded_capacity: a sender-controlled counter never drives aVec::with_capacityunbounded. - Errors in a dedicated file, with
thiserror, carrying the offending values. Never a bareString. - Checks in a separate file under
src/checks, not inline in the parser. - The main struct's rustdoc documents the wire format with a Mermaid
packet-betadiagram. - No
unwrap()in a parser, and noascast that can truncate: a length read from the wire goes throughusize::fromortry_from. The CI runs clippy with-D warningsand theunwrap_used/expect_used/paniclints, joined in 12.1.0 bycast_possible_truncation. - Golden tests use real frames from a capture under
pcaps_exemple/, with the pcap file and frame number cited in a comment. Synthetic bytes are for targeted unit tests (truncation, invalid value, limits) and are labelled as such.
The first principle drawn on FooPacket, the example this chapter builds, with the file each part lives in. This is the shape the method asks of every parser: a straight line, where every exit before the struct is a typed error.
Files to create
For an application protocol foo:
src/parse/application/protocols/foo.rs the struct and its TryFrom
src/errors/application/foo.rs enum FooError
src/checks/application/foo.rs validate_* / extract_*
pcaps_exemple/protocols/foo/ a real capture + SOURCE.md
and one pub mod foo; in each layer's mod.rs.
1. The error type
#![allow(unused)] fn main() { use thiserror::Error; #[derive(Debug, Error, PartialEq)] #[non_exhaustive] pub enum FooError { #[error("Packet too short: expected at least {expected} bytes, got {actual} bytes")] InvalidLength { expected: usize, actual: usize }, #[error("Invalid Foo version: {0}")] InvalidVersion(u8), #[error("Invalid Foo message type: {0}")] InvalidMessageType(u8), } }
2. The checks
#![allow(unused)] fn main() { const FOO_MIN_LENGTH: usize = 8; pub fn validate_foo_min_length(packet: &[u8]) -> Result<(), FooError> { if packet.len() < FOO_MIN_LENGTH { return Err(FooError::InvalidLength { expected: FOO_MIN_LENGTH, actual: packet.len() }); } Ok(()) } pub fn extract_foo_version(byte: u8) -> Result<u8, FooError> { let version = byte >> 4; if version != 1 { return Err(FooError::InvalidVersion(version)); } Ok(version) } }
3. The parser
#![allow(unused)] fn main() { /// Foo Protocol Packet /// /// ```mermaid /// packet-beta /// 0-3: "Version u4" /// 4-7: "Flags u4" /// 8-15: "Message Type u8" /// 16-31: "Length u16" /// 32-63: "Payload variable" /// ``` #[derive(Debug, PartialEq)] #[non_exhaustive] pub struct FooPacket<'a> { pub version: u8, pub message_type: u8, pub length: u16, pub payload: &'a [u8], } impl<'a> TryFrom<&'a [u8]> for FooPacket<'a> { type Error = FooError; fn try_from(packet: &'a [u8]) -> Result<Self, Self::Error> { validate_foo_min_length(packet)?; let version = extract_foo_version(packet[0])?; let message_type = packet[1]; let length = u16::from_be_bytes([packet[2], packet[3]]); validate_foo_announced_length(packet, length)?; Ok(FooPacket { version, message_type, length, payload: &packet[4..length as usize] }) } } }
4. Plugging it into the dispatch table
Add a variant Foo at the end of ApplicationProtocol, with its label, in src/parse/application/protocol.rs, and the label to the test labels_are_frozen of the same file. Add a ProbeId::Foo at the end of the enum, where it becomes ProbeId::LAST, and its run_probe arm, in src/parse/dispatch/probes.rs. Failures are memoized in a u128, one bit per probe: 67 are taken, 128 is the limit. Then add one line in RULES, in src/parse/dispatch/rules.rs, choosing the route described in the application chapter:
- blind
rule(ApplicationProtocol::Foo, Guard::Tcp, ProbeId::Foo)only if a valid Foo payload cannot also be a valid payload of another detected protocol, or arbitrary text; - port-guarded
port_rule(..)otherwise, with a comment explaining why; - always with the transport guard the RFC imposes.
The position in the table matters: put the line where its priority belongs and say why in a comment. The unit test blind_rules_order_is_frozen of dispatch/tests.rs lists, in order, the labels of every rule without a port guard: a blind rule adds its own there. A blind probe is tested without a frame by classify_payload(<transport>, None, None, payload), under the transport of its guard. A port-guarded protocol usually gets a DecodeAsProtocol variant as well, at the end of the enum, which DecodeAsProtocol::rule resolves to the label and the probe of its port rule; decode_as_protocols_resolve_to_table_rules checks the pair (Decode As), and the parse_packetflow fuzz target reads DecodeAsProtocol::ALL, so the new variant is fuzzed without a change. Then update the protocol lists of README.md and README-fr.md.
Do not add a variant to an exhaustive public enum in a minor version: that breaks users' match. The types the parser builds are #[non_exhaustive] so that new fields and variants stay additive.
5. Tests
Minimum for the unit tests: a valid packet, a too-short packet, an invalid version, an invalid announced length, an invalid type or flag.
Then, at PacketFlow level:
- at least one golden test on a real frame (Ethernet + IP + transport + Foo) checking that the label comes out;
- for a port-guarded protocol, the non-detection of the same bytes off the standard port;
- for a blind probe, a scan of the other protocols' corpus with a non-empty negative oracle, keyed by expected frame numbers so that a false positive and a false negative cannot cancel each other out;
- a structured valid seed in the relevant fuzz target: random bytes rarely get through Ethernet + IP + transport + Foo. A target of its own,
fuzz/fuzz_targets/parse_foo.rs, needs its[[bin]]infuzz/Cargo.toml: the CI refuses a target file without one, and the nightly matrix is drawn from these entries (data validation).
Extract a payload from a capture with:
tshark -r capture.pcap -Y "frame.number==5" -T fields -e tcp.payload
6. Checklist before commit
cargo fmt --all -- --check
cargo test --workspace --all-features
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo +nightly fuzz build
cargo audit
cargo deny check --hide-inclusion-graph
cargo semver-checks check-release # public API vs the last published version
Custom parsers and rules
The crate names the protocols it decodes. For one it does not decode, a proprietary format or an in-house protocol, the caller can add a parser of its own. There are three ways:
| Way | Since | What it is | What it can do |
|---|---|---|---|
| A Rust parser | 13.0.0 | a type that implements ApplicationParser, registered with ParseConfig::with_parser | anything Rust can do |
| A plugin | 13.0.0 | the same type, compiled into a native library (.so, .dylib, .dll) loaded at run time | anything, with every right of the process |
| A rule file | 13.1.0 | a TOML file read at run time, behind the rules feature | recognize byte patterns at fixed offsets, and show fields at fixed offsets |
A rule file runs no code, and that is its point. What a reviewer reads is exactly what runs: an application that must show it is passive can load rules where it cannot load native code.
The examples of this chapter use ACME and DEMO, two made-up protocols.
What an added parser can do
An added parser runs after the dispatch table, and only on a payload the table left "Unknown":
- a non-empty TCP or UDP payload;
- of a flow at any level, the inner flows of a tunnel included;
- with the transports and ports the parser declares.
It never takes a payload from the crate: an SSH banner stays "SSH" even if every parser accepts it. The parsers run in the order they were registered. The first one that accepts the payload names the flow ApplicationProtocol::Custom(label), and the JSON output writes that label like any other: "application_protocol": "ACME".
It cannot read a protocol carried by something other than TCP or UDP, reassemble a stream, rename a protocol the crate recognizes, or see the flows the table names.
A Rust parser
The trait has five methods. Only label and matches have no default (tested):
#![allow(unused)] fn main() { /// ACME: datagrams on UDP 47000 that start with `ACME`. struct Acme; impl ApplicationParser for Acme { fn label(&self) -> &'static str { "ACME" } fn transports(&self) -> CustomTransports { CustomTransports::Udp // TCP and UDP by default } fn ports(&self) -> &[u16] { &[47_000] // any port by default } fn matches(&self, payload: &[u8], _context: &PayloadContext) -> bool { payload.starts_with(b"ACME") } fn fields(&self, payload: &[u8], _context: &PayloadContext) -> Vec<(String, String)> { match payload.get(5) { Some(kind) => vec![("type".to_string(), kind.to_string())], None => Vec::new(), } } } }
matches is called on many payloads. It must be fast and decide from the bytes and the context alone: no file, no network, no clock, no global state. It must not panic: a parser registered in the application has no net. A signature too weak to stand alone, such as two magic bytes, should come with a port list.
fields is not called while parsing. The application asks for the fields when it shows one packet, with ParseConfig::custom_fields(&flow) (tested):
#![allow(unused)] fn main() { #[test] fn an_added_parser_names_what_the_table_left_unknown() { let frame = udp_frame(47_000, ACME_REQUEST); let flow = parse(LinkType::ETHERNET, &frame).unwrap(); assert_eq!(protocol(&flow), Some(ApplicationProtocol::Unknown)); let config = ParseConfig::new().with_parser(Arc::new(Acme)).unwrap(); let flow = parse_with(LinkType::ETHERNET, &frame, &config).unwrap(); assert_eq!(protocol(&flow), Some(ApplicationProtocol::Custom("ACME"))); assert_eq!(protocol(&flow).unwrap().label(), "ACME"); // The fields are read on demand, when a packet is shown. let fields = config.custom_fields(&flow).unwrap(); assert_eq!(fields, [("type".to_string(), "1".to_string())]); // The port list is a guard: on another port the parser is not called. let elsewhere = udp_frame(47_001, ACME_REQUEST); let flow = parse_with(LinkType::ETHERNET, &elsewhere, &config).unwrap(); assert_eq!(protocol(&flow), Some(ApplicationProtocol::Unknown)); } }
The label is checked on registration (ParserRegistrationError). It is refused when it is empty, longer than 64 bytes, has a control character or spaces around it, is the label of a built-in protocol, or is already registered. The last two comparisons ignore ASCII case. A parser that accepts everything shows the guarantee (tested):
#![allow(unused)] fn main() { /// A parser that accepts every payload, on every transport and port. struct Everything; impl ApplicationParser for Everything { fn label(&self) -> &'static str { "EVERYTHING" } fn matches(&self, _payload: &[u8], _context: &PayloadContext) -> bool { true } } #[test] fn an_added_parser_never_takes_a_frame_from_the_crate() { let config = ParseConfig::new().with_parser(Arc::new(Everything)).unwrap(); // The GIOP request of corba.pcap stays GIOP: the table named it. let raw = hex::decode(ETHERNET_IPV4_TCP_GIOP_REQUEST_HEX).unwrap(); let flow = parse_with(LinkType::ETHERNET, &raw, &config).unwrap(); assert_eq!(protocol(&flow), Some(ApplicationProtocol::Giop)); assert_eq!(config.custom_fields(&flow), None); // A label of the crate is refused, whatever its case. struct FakeDns; impl ApplicationParser for FakeDns { fn label(&self) -> &'static str { "dns" } fn matches(&self, _payload: &[u8], _context: &PayloadContext) -> bool { false } } assert!(ParseConfig::new().with_parser(Arc::new(FakeDns)).is_err()); } }
ParseConfig has the rest of the API:
| Method | What it does |
|---|---|
with_parser(parser) | adds a parser, by value |
add_parser(&mut self, parser) | adds a parser to an existing configuration; a refusal leaves it unchanged |
remove_parser(label) | removes a parser and returns it |
parser(label) | returns a parser |
parser_labels() | lists the labels, in the order they run |
custom_fields(&flow) | the fields of a flow an added parser named; None otherwise |
application_protocol(label) | reads a stored label back (13.1.0) |
classify_payload_with goes through the same parsers.
Reading a stored label back
An application that stores its labels as text, in an export or a flow matrix, must read them back. FromStr knows only the labels of the crate: it refuses a custom label, since the text does not say which parser gave it. Since 13.1.0, config.application_protocol(label) answers with the configuration that produced the label (#323). The comparison is exact, case included. A parser removed since the export gives UnknownApplicationLabel, and the application decides whether to keep the text or to report the missing parser (tested):
#![allow(unused)] fn main() { #[test] fn a_stored_label_reads_back_with_its_configuration() { let mut config = ParseConfig::new().with_parser(Arc::new(Acme)).unwrap(); // `FromStr` knows the labels of the crate, not those of a configuration. assert_eq!("DNS".parse::<ApplicationProtocol>(), Ok(ApplicationProtocol::Dns)); assert!("ACME".parse::<ApplicationProtocol>().is_err()); // The configuration knows both. The comparison is exact, case included. assert_eq!(config.application_protocol("DNS"), Ok(ApplicationProtocol::Dns)); assert_eq!(config.application_protocol("ACME"), Ok(ApplicationProtocol::Custom("ACME"))); assert!(config.application_protocol("acme").is_err()); // A parser removed since the export: the label no longer reads back. config.remove_parser("ACME"); assert!(config.application_protocol("ACME").is_err()); } }
A plugin
A plugin is a cdylib crate that calls export_parser! once on a type that implements ApplicationParser. The host loads it with load_parser, which checks what the library declares: the entry point, the version of the ABI (packet_parser_plugin_v1), the size of the descriptor, the label, the transports and the ports. A panic of the parser is caught at the boundary, and the payload is then not recognized.
Both sides are in the kit packet_parser_plugin, in the plugin/ folder of the crate repository. The kit is not published on crates.io: a plugin depends on it through git or a path. It is the only unsafe code of the repository, outside the published crate.
A plugin is native code, not a sandbox. Once loaded, it can read the memory and the files of the application, use the network, and crash it by a fault other than a panic. load_parser is unsafe for that reason: the kit checks the shape of what the plugin declares, not what its code does. Load only a library whose origin you checked. docs/plugins.md, in the crate repository, has the build, the loading and the advice for an "Import parsers" button.
A rule file
The feature is off by default. Without it, the crate does not depend on toml:
[dependencies]
packet_parser = { version = "13.1", features = ["rules"] }
RuleSet::from_toml reads and checks a whole file. ParseConfig::with_rules and add_rules then register one parser per label, every label of the file or none. A label stored as text reads back with application_protocol, as above (tested):
#![allow(unused)] fn main() { const ACME_RULES: &str = r#" version = 1 [[rule]] label = "ACME" transport = "udp" ports = [47000] min_length = 12 [[rule.pattern]] offset = 0 bytes = "41 43 4D 45" # "ACME" [[rule.pattern]] offset = 4 bytes = "01" mask = "0F" # version 1 in the low nibble [[rule.field]] name = "type" offset = 5 type = "u8" values = { 1 = "request", 2 = "response", 0x7F = "error" } [[rule.field]] name = "length" offset = 6 type = "u16be" [[rule.field]] name = "id" offset = 8 type = "hex" length = 4 "#; #[test] fn a_rule_file_names_and_shows_a_protocol_without_code() { let rules = RuleSet::from_toml(ACME_RULES).unwrap(); assert_eq!(rules.labels().collect::<Vec<_>>(), ["ACME"]); let config = ParseConfig::new().with_rules(&rules).unwrap(); let frame = udp_frame(47_000, ACME_REQUEST); let flow = parse_with(LinkType::ETHERNET, &frame, &config).unwrap(); assert_eq!(protocol(&flow), Some(ApplicationProtocol::Custom("ACME"))); let fields = config.custom_fields(&flow).unwrap(); let shown: Vec<String> = fields.iter().map(|(name, value)| format!("{name}: {value}")).collect(); assert_eq!(shown, ["type: request (1)", "length: 12", "id: DE AD BE EF"]); // Version 2 in the low nibble: the second pattern fails. let mut version_2 = ACME_REQUEST.to_vec(); version_2[4] = 0x02; let frame = udp_frame(47_000, &version_2); let flow = parse_with(LinkType::ETHERNET, &frame, &config).unwrap(); assert_eq!(protocol(&flow), Some(ApplicationProtocol::Unknown)); } }
Recognizing a payload
A rule recognizes a payload when every condition holds:
- the transport is one of
transport:"tcp","udp"or"tcp+udp", the default; - the source or the destination port is in
ports, when it is given; - the length is between
min_length, by default the end of the last pattern, andmax_length; - each pattern holds: for each byte
i,payload[offset + i] & mask[i] == bytes[i]. Withoutmask, every bit counts.
Several rules with the same label are variants of one protocol, such as a request and a response. The label goes to a payload that any of them recognizes, and the fields are those of the first that does. The labels of a file run in the order of their first rule.
Fields
type | Shown as | Keys |
|---|---|---|
u8, u16be, u16le, u32be, u32le, u64be, u64le | an unsigned integer, in decimal; request (1) when values names it | optional mask, values |
hex | the bytes in hexadecimal: DE AD BE EF | length, required |
text | the bytes up to the first NUL: printable ASCII as is, \ as \\, any other byte as \xNN | length, required |
mask on an integer keeps some bits and shifts them down: for a u16be, mask = "0F F0" turns 0x1234 into 0x23. A field that does not fit in the payload is not shown: nothing is made up.
What is refused
The file is refused at its first mistake. RulesError gives the line, the column and the reason, in French. A rule must check at least 16 bits with its patterns. Below that, a random payload matches more than once in 65 536, and a busy network would show the label on traffic that is not the protocol. A rule on a port alone is therefore impossible: a port is a convention, not proof (tested):
#![allow(unused)] fn main() { #[test] fn a_rule_on_a_port_and_one_byte_is_refused() { // 8 bits of pattern: a random payload would match once in 256. let weak = "version = 1\n\n[[rule]]\nlabel = \"ACME\"\nports = [47000]\n\n\ [[rule.pattern]]\noffset = 0\nbytes = \"41\"\n"; let error = RuleSet::from_toml(weak).unwrap_err(); assert_eq!(error.line(), Some(3)); assert!(error.message().starts_with("signature trop faible : 8 bits")); // A typo is an unknown key, refused where it is. let typo = ACME_RULES.replace("mask = \"0F\"", "masq = \"0F\""); let error = RuleSet::from_toml(&typo).unwrap_err(); assert!(error.to_string().starts_with("ligne 17, colonne 1 : ")); } }
The other refusals:
| Mistake | Why it is refused |
|---|---|
| a key the format does not have | a typo such as masq would drop a condition without a word |
version missing, or other than 1 | the format can change only with a new version |
| a label invalid, built-in, or equal to another of the file but for case | the rules of a Rust parser's label |
| a rule without a pattern | — |
invalid hexadecimal, a mask of another length than its bytes, a byte with bits outside its mask, a mask of zeros | a pattern that cannot match, or matches anything |
min_length before the end of a pattern, max_length below min_length | a rule that can never match |
a field with an unknown type, a length it does not use or lacks, mask or values on a non-integer, a value it can never hold, a value or a field name used twice | — |
Each file has bounds:
| Bound | Value |
|---|---|
offset of a pattern or a field | 65 535 |
bytes of a pattern | 64 bytes |
length of a hex or text field | 256 bytes |
| rules in a file | 256 |
ports of a rule | 256 |
| fields of a rule | 64 |
values of a field | 256 |
| name of a field or a value | 64 bytes |
What a rule cannot do
- Read a protocol carried by something other than TCP or UDP: the payload of a proprietary EtherType is out of reach.
- Follow a position read from the payload: a length, a TLV, a repeated structure. Positions are fixed.
- Reassemble a stream. On TCP, only the segment that starts a message is recognized, and the segments after it stay
"Unknown". - Rename what the crate recognizes.
A protocol that needs any of these deserves a decoder in the crate (Adding a new protocol).
Cost
A rule is tried only on payloads the crate left "Unknown", so a file costs nothing on traffic the crate recognizes. On an "Unknown" payload, the length bounds and the most selective byte of each rule turn away almost every payload of another protocol before the patterns are read. Measured on the corpus of the crate repository, 384 395 frames whose flows are 14 % "Unknown", with rules that match none of them:
| Labels | Cost per "Unknown" flow | Whole corpus |
|---|---|---|
| 1 | 27 ns | +1.2 % |
| 5 | 58 ns | +2.4 % |
| 20 | 220 ns | +9.3 % |
| 50 | 460 ns | +18.6 % |
Trying a rule file
The crate repository has a command-line tool, examples/rules_check.rs:
cargo run --release --features rules --example rules_check -- \
site-rules.toml capture1.pcapng capture2.pcap --fields 3
It prints every mistake of the file with its line, the number of flows each label names, the number of "Unknown" flows before and after the rules, and with --fields N the fields of the first N flows of each label. It fails if a flow that the crate had named changed label, which would be a defect of the crate. examples/acme_rules.toml is a complete file, with ACME and DEMO.
Confidential rules
The rules of a confidential protocol never need to leave the machine they are written on:
- the rule file is data that the application reads at start-up, not part of the crate, of the application's source or of its build;
rules_checkreads only the files on its command line and writes only to the terminal;- a problem with the feature is reported with made-up bytes, as ACME and DEMO are.
Recording which rules produced a result is the application's job: it can store the name and a digest of the file it loaded.
If a later version of the crate decodes a protocol under the label of a rule, RuleSet::from_toml refuses the file, since the label is now built in. The crate's decoder then names the traffic: remove the rule, or rename it.
Glossary
The words the book relies on, each with the page that puts it to work.
Added parser
A parser the caller registers in ParseConfig, in Rust, in a plugin, or as a rule file. It runs after the table, on a TCP or UDP payload the table left "Unknown", and its label is ApplicationProtocol::Custom. See Custom parsers and rules.
Blind
A blind rule has no port guard: its probe runs on any port, and the content alone gives the label. A blind probe is stricter than the probe of the same protocol behind a port. See Three detection routes.
Corpus
The real captures of the crate, under pcaps_exemple/, each with its provenance in a SOURCE.md. The golden tests and the oracles run on it. See Adding a new protocol.
Corrupted layer
A layer that a lower layer announced and whose bytes were refused. It stays None, and PacketFlow::corrupted names it and carries the error, typed since 13.0.0. See Reading the outcome.
Decode As
A port the caller declares for a protocol, through ParseConfig. It extends a port guard and never replaces the probe: the content must still match. See "Decode As".
Flow identity
The MAC addresses, IP addresses, protocols and ports of a packet. PacketFlow compares and hashes on it, not on the payloads. See Flow identity.
Golden test
A test of the crate that parses real frames of the corpus and compares the result with values frozen in the repository. See Adding a new protocol.
Inner flow
The PacketFlow of the packet a tunnel carries, held in the inner field of the outer flow. See Tunnels.
Label
The name the crate gives the application protocol of a flow: a variant of ApplicationProtocol, written as text in the JSON output. See Protocols.
Oracle
The output of tshark on the corpus, frozen in a file of the repository. A golden test compares the crate with it, field by field. See Protocols.
Owned flow
PacketFlowOwned, the form of a flow that does not borrow the capture buffer. It keeps the identity and drops the payloads and the details. See Owned flows and serialization.
Port guard
The list of ports of a rule. The rule is tried only when the source or the destination port is in the list. See Reading the table.
Probe
The function that says whether a payload is a given protocol. It usually runs the decoder of the protocol and keeps only the verdict. See How the label is chosen.
PROBE_CAP
The number of bytes a text probe reads, 18 KiB. Only the FTP, SMTP, NNTP and HTTP probes stop there; every other probe reads the whole payload. See How the label is chosen.
Rule
One row of the dispatch table: a label, a transport guard, an optional port guard and a probe. The rules are tried in order, and the first whose probe accepts the payload gives the label. See Reading the table.
Stateless
parse reads one packet and keeps nothing between two calls: no reassembly, no memory of a flow. See Limits.
Tile
Messages tile a payload when each one starts where the previous one ends and the last one ends at the last byte. A blind probe on TCP often asks for it, since a segment may carry several messages. See Tightening a blind probe.
Terminal port
A port whose rule ends the dispatch when its probe refuses the payload: the flow gets no label, and no later rule is tried. mDNS (5353) and LLMNR (5355) are the two. See Reading the table.
Transport guard
The transport a rule accepts: Tcp, Udp or Any. See Reading the table.
Truncated
A message whose end is in a later segment. The decoders that tile a segment keep its beginning and set truncated on it. See Limits.
Whole payload
What a probe judges: every byte the transport layer hands up, not a prefix. Most decoders want the payload tiled to its last byte. See How the label is chosen.
About
packet_parser and this book are written by Cyprien Avico (LinkedIn).
- The repository of the crate: Akmot9/Packet-parser
- The crate: crates.io, packet_parser
- The API reference: docs.rs, packet_parser
The API reference says what each item is. This book says how the crate reads a packet, and why it reads it that way.
Corrections are welcome, as an issue or a pull request on the repository of the book.