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

The APDU of frame 9 of wireshark_iec104.pcap, 32 bits per row: the APCI with its start byte 0x68, length 14 and four control bytes announcing an I-format frame with send and receive sequence numbers 0, then the ASDU: type 100 (C_IC_NA_1), SQ 0 with one object, cause of transmission 6 (activation), originator 0, common address 10, the information object address 0 and the qualifier of interrogation 20; Iec104Packet keeps one Apdu with its format and its decoded Asdu.

#![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].

BytesFieldNote
0start0x68, otherwise InvalidStartByte
1lengththe control field and the ASDU: 4 to 253, otherwise InvalidLength
2–5controlread according to the format, which the two low bits of byte 2 give
FormatByte 2, low bitsWhat the crate readsApciFormat
Ix0N(S) in bytes 2–3 and N(R) in bytes 4–5, each shifted left by one bitInformation { send_sequence, receive_sequence }
S01N(R) in bytes 4–5Supervisory { receive_sequence }
U11the function bits of byte 2Unnumbered(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 ASDUFieldNote
0type_idnamed by kind
1sequence (bit 7), count (bits 0–6)a count of zero is EmptyAsdu(type_id)
2cause (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
3originatororiginator address
4–5common_addresslittle-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:

ErrorWhen
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 countsNumber
segments with a payload, all on port 2404, all labelled "IEC 104"374
of them, compared with tshark373
APDUs448
ASDUs, of 27 types301
information objects668
ASDUs in sequence46
cut APDUs0

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.

CaptureFramesContentOrigin
wireshark_iec104.pcap105a 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 51Wireshark wiki
wireshark_IEC104_SQ.pcapng1one segment of four M_SP_NA_1 in sequence, sixteen points eachWireshark wiki
iti_090813_diverse.pcap173a 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.pcap357two masters and one station (2008): repeated interrogations, answers in sequence, one retransmissionITI ICS-Security-Tools
ndpi_IEC104.pcap15time-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.