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.

A DNS response, 32 bits per row: the 12-byte header with its transaction identifier, flags and four counts, the question wireshark.org with its type and class, then one answer whose name is a two-byte compression pointer to offset 12, followed by type, class, TTL, data length and four bytes of address; on the right the DnsPacket struct, with the header, the question, and the answer whose name is rebuilt

Detection: five rules, three labels

RuleLabelTransportPortConstructor
11mDNSUDP5353, terminalDnsPacket::try_from_mdns
12LLMNRUDP5355, terminalDnsPacket::try_from_llmnr
22DNSTCP53DnsPacket::try_from_tcp
23DNSUDP53DnsPacket::try_from
53DNSUDPnoneDnsPacket::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:

RuleRefused as
A pointer must point strictly backwardsDnsQueryParseError::InvalidCompressionPointer
At most 8 pointers are followed for one nameInvalidCompressionPointer
A length byte starting with 01 or 10 is reservedReservedLabelType
A name is at most 255 bytes on the wire, the labels reached through pointers includedOutOfBoundParse

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.

BytesFieldCheckError
0–11Headerthe message holds at least 12 bytesDnsPacketError::InsufficientData
2–3Flags, bit 6the one bit still reserved is zero; AD and CD are freeDnsFlagsError::InvalidZField
2–3Flags, opcode0 to 5InvalidOpcode
2–3Flags, RCODE0 to 5InvalidRCode
2–3Flags, RAzero in a queryRaInQuery
2–3Flags, AA and TCzero in the response to a STATUS requestAaTcInStatusResponse
2–3Flags, AAzero when the response code is 2 (server failure) or 5 (refused)AaInServerFailure, AaInRefused
4–11Countsno record without a questionDnsHeaderError::InvalidCounts
12–Questionseach name follows the rules above, and four bytes of type and class follow itDnsQueryParseError
afterRecordseach name, then ten bytes of type, class, TTL and data length, then that many bytes of dataDnsQueryParseError

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 NOTAUTH is 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_tcp reads 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.