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.