DNS - Domain Name System

pcapkit.protocols.application.dns.protocol contains DNS only, which implements an extractor for Domain Name System (DNS) messages [RFC 1035], whose header is:

Octets

Bits

Name

Description

0

0

dns.length

Message Length (over TCP only)

0

0

dns.id

Identifier

2

16

dns.flags

QR, Opcode, AA, TC, RD, RA, Z, AD, CD, RCODE

4

32

dns.qdcount

Question Count

6

48

dns.ancount

Answer Count

8

64

dns.nscount

Authority Count

10

80

dns.arcount

Additional Count

Over TCP, the two-octet length precedes the message, so every offset above moves two octets on (RFC 1035 Section 4.2.2, RFC 7766 Section 8).

How a parse reads a message:

        flowchart TD
    IN["octets at port 53"] --> GIVEN{"framed= given?"}
    GIVEN -->|yes| READ["read as it says"]
    GIVEN -->|no| WHOLE{"a whole message that fits<br/>behind a length field?"}
    WHOLE -->|no| UNFRAMED["one message, unframed"]
    WHOLE -->|yes| PLAIN{"do the sections the header<br/>counts fit the octets?"}
    PLAIN -->|no| FRAMED["one message, framed"]
    PLAIN -->|yes| EXACT{"does the framed one end<br/>exactly at its length?"}
    EXACT -->|no| UNFRAMED
    EXACT -->|yes| END{"does the plain one stop<br/>short of the end?"}
    END -->|yes| FRAMED
    END -->|no| TIE{"a question in the framed one only,<br/>or a further exact framed message?"}
    TIE -->|yes| FRAMED
    TIE -->|no| UNFRAMED
    FRAMED --> NEXT{"a whole framed message after it?"}
    NEXT -->|yes| CHAIN["a further DNS layer"]
    NEXT -->|no| REST["the rest as Raw"]
    

Added in version 1.7.0.


class pcapkit.protocols.application.dns.protocol.DNS(file, length=None, /, *, framed=None, layer=None, protocol=None, context=None)[source]

Bases: Application[DNS, DNS]

This class implements Domain Name System.

Overloads:

A message is parsed whole: the header, the four sections, the RDATA of the types __rdata__ registers and the options of the OPT pseudo-record of EDNS(0) (RFC 6891) that __option__ registers. Each domain name records the compression it was read with (Name), so a message rebuilds as captured.

Over TCP the two-octet length precedes the message, which framed=True reads and writes. A parse not given framed reads the length where a whole message decodes behind it and the octets read worse as a plain message, as _frames_message() weighs them, much as TLS tries SSLv2 on what its own parser refuses (The SSL Family): the port the transport dispatches on is the same for TCP and UDP. A further whole message after a framed one is dissected as another DNS layer, the previous one’s payload, as TLS records are; a message the segment ends inside is not reassembled and stays Raw.

The RDATA each type carries:

RR Type

Data Model

A

A

NS

NS

CNAME

CNAME

SOA

SOA

PTR

PTR

MX

MX

TXT

TXT

AAAA

AAAA

SRV

SRV

OPT

OPT, the whole record

CAA

CAA

Any other type, and RDATA its decoder cannot read exactly, is kept as raw octets. The EDNS(0) options decoded are edns-client-subnet (ClientSubnet), COOKIE (Cookie), edns-tcp-keepalive (TCPKeepalive) and Extended DNS Error (ExtendedError); any other is kept as raw octets.

Defaults

__rdata__: DefaultDict[RRType | int, str | tuple[Callable[[RRType, bytes, bytes, int], RData | bytes], Callable[[RRType, Mapping[str, Any], int, dict[tuple[bytes, ...], int] | None], bytes]]]

RR type to method mapping, see _read_dns_record() and _make_dns_record(). A str value names the methods _read_rdata_${name} and _make_rdata_${name}, falling back to _read_rdata_unknown() and _make_rdata_unknown() when the class has no such method; any other value is a (parser, constructor) pair of callables. The OPT pseudo-record is read whole by _read_dns_opt(), outside this map.

__option__: DefaultDict[Option | int, str | tuple[Callable[[Option, bytes], OptionData | bytes], Callable[[Option, Mapping[str, Any]], bytes]]]

EDNS(0) option code to method mapping, see _read_dns_options() and _make_dns_options(). A str value names the methods _read_opt_${name} and _make_opt_${name}, falling back to _read_opt_unknown() and _make_opt_unknown(); any other value is a (parser, constructor) pair of callables.

Properties

property name: Literal['Domain Name System']

Name of current protocol.

property length: int

Header length of current protocol, i.e. the message with its TCP length field.

property rcode: RCode | int

Response code, extended by the OPT pseudo-record’s upper bits if any (RFC 6891 Section 6.1.3).

Methods

read(length=None, **kwargs)[source]

Read Domain Name System.

Structure of DNS header [RFC 1035]:

                                1  1  1  1  1  1
  0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                      ID                       |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR|   Opcode  |AA|TC|RD|RA| Z|AD|CD|   RCODE   |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                    QDCOUNT                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                    ANCOUNT                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                    NSCOUNT                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                    ARCOUNT                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Parameters:
  • length (int | None) – Length of packet data.

  • **kwargs (Any) – Arbitrary keyword arguments.

Return type:

DNS

Returns:

Parsed packet data.

Raises:

ProtocolError – If the TCP length field counts fewer octets than the header, or a section entry runs past the message or holds a malformed domain name.

make(*, id=0, qr=False, opcode=Opcode.Query, aa=False, tc=False, rd=False, ra=False, z=0, ad=False, cd=False, rcode=RCode.NoError, question=(), answer=(), authority=(), additional=(), framed=False, message_length=None, compress=False, trailer=b'', payload=b'', **kwargs)[source]

Make (construct) packet data.

The section counts are those of the entries given. A question entry is a mapping of name, type and class, as Question is. A record is a mapping of name, type, class, ttl, rdlength and rdata, as ResourceRecord is, or, for the OPT pseudo-record, of the fields of OPT. rdata is raw octets, or a mapping of the fields of the type’s data model, as __rdata__ registers it. A name is a Name, which writes the compression it records, its labels, or its presentation form.

Parameters:
  • id (int) – Identifier.

  • qr (bool) – Whether the message is a response.

  • opcode (Opcode | int) – Kind of query.

  • aa (bool) – Authoritative answer.

  • tc (bool) – Truncation.

  • rd (bool) – Recursion desired.

  • ra (bool) – Recursion available.

  • z (int) – Reserved bit.

  • ad (bool) – Authentic data.

  • cd (bool) – Checking disabled.

  • rcode (RCode | int) – Response code, the header’s four bits.

  • question (Iterable[Mapping[str, Any]]) – Question section.

  • answer (Iterable[Mapping[str, Any]]) – Answer section.

  • authority (Iterable[Mapping[str, Any]]) – Authority section.

  • additional (Iterable[Mapping[str, Any]]) – Additional section.

  • framed (bool) – Whether to write the TCP length field.

  • message_length (int | None) – TCP length field, written whenever given; the message’s own length otherwise.

  • compress (bool) – Whether to compress the names given as labels or text against those written before them (RFC 1035 Section 4.1.4), where the type allows it.

  • trailer (bytes) – Octets of the message past its last record.

  • payload (bytes | ProtocolBase | Schema) – Payload data, after the message.

  • **kwargs (Any) – Arbitrary keyword arguments.

Return type:

DNS

Returns:

Constructed packet data.

Raises:

ProtocolError – If a field does not fit its width, an enumeration field is a name or a bool for a field wider than a bit, a name is malformed, or rdata is a mapping for a type with no constructor.

classmethod register_option(code, meth)[source]

Register an EDNS(0) option parser.

Parameters:
Warns:

RegistryWarning – If a different entry is already registered for code; it is overwritten. Handing back the entry already stored, or one equal to it, is a silent no-op.

classmethod register_rdata(code, meth)[source]

Register an RDATA parser.

Parameters:
Warns:

RegistryWarning – If a different entry is already registered for code; it is overwritten. Handing back the entry already stored, or one equal to it, is a silent no-op.

Data Models

classmethod __index__()[source]

Numeral registry index of the protocol.

Return type:

int

Returns:

Numeral registry index of the protocol in IANA service names and port numbers: port 53, the port of UDP.domain as an int, at which UDP.__proto__ and TCP.__proto__ dispatch here (The Registry Index).

__init__(file=NO_VALUE, length=None, /, *, framed=None, layer=None, protocol=None, context=None, **fields)[source]

Parse a protocol instance from its octets, or construct one from its fields.

Overloads:
Parameters:

Changed in version 1.8.0: Declares framed, its only parse keyword besides the stops and the context (#2840).

__post_init__(file=None, length=None, **kwargs)[source]

Post initialisation hook.

Parameters:
  • file (Any | None) – Source packet stream.

  • length (int | None) – Length of packet data.

  • framed (Optional[bool]) – Parsing, whether the TCP length field precedes the message. When not given, it does where _frames_message() finds a whole message behind a length field that reads better than the octets as a plain one, which is how a TCP segment carries one.

  • **kwargs (Any) – Arbitrary keyword arguments.

Return type:

None

See also

self.make for the construction arguments.

Utilities

classmethod _make_data(data)[source]

Create key-value pairs from data for protocol construction.

Parameters:

data (DNS) – protocol data

Return type:

dict[str, Any]

Returns:

Key-value pairs for protocol construction.

_read_dns_question(message, pos)[source]

Read a question section entry.

Structure of a question entry [RFC 1035 Section 4.1.2]:

                                1  1  1  1  1  1
  0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/                     QNAME                     /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                     QTYPE                     |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                     QCLASS                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Parameters:
  • message (bytes) – The message, from its header on.

  • pos (int) – Offset of the entry in message.

Return type:

tuple[Question, int]

Returns:

The entry, and the offset just past it.

_make_dns_question(entry, *, offset, table)[source]

Make a question section entry.

Parameters:
  • entry (Mapping[str, Any]) – The entry’s name, type and class.

  • offset (int) – Offset of the entry in the message.

  • table (dict[tuple[bytes, ...], int] | None) – Names written so far, when compressing.

Return type:

bytes

Returns:

The entry’s octets.

_read_dns_record(message, pos)[source]

Read a resource record.

Structure of a resource record [RFC 1035 Section 4.1.3]:

                                1  1  1  1  1  1
  0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/                      NAME                     /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                      TYPE                     |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                     CLASS                     |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                      TTL                      |
|                                               |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|                   RDLENGTH                    |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
/                     RDATA                     /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+

The RDATA is read by the parser __rdata__ registers for its type. Its length delimits it, so RDATA its parser rejects with a ProtocolError is kept as raw octets, quietly, as a TLS extension body is.

Parameters:
  • message (bytes) – The message, from its header on.

  • pos (int) – Offset of the record in message.

Return type:

tuple[ResourceRecord | OPT, int]

Returns:

The record, and the offset just past it.

_make_dns_record(record, *, offset, table)[source]

Make a resource record, or the OPT pseudo-record.

Parameters:
Return type:

bytes

Returns:

The record’s octets.

_read_rdata_unknown(rr_type, data, *, message, offset)[source]

Read an RDATA with no decoder registered: its raw octets.

Parameters:
  • rr_type (RRType) – RR type.

  • data (bytes) – RDATA octets.

  • message (bytes) – The message, for the names inside.

  • offset (int) – Offset of data in message.

Return type:

bytes

Returns:

data itself.

_read_rdata_a(rr_type, data, *, message, offset)[source]

Read an A RDATA (RFC 1035 Section 3.4.1).

Parameters:
  • rr_type (RRType) – RR type.

  • data (bytes) – RDATA octets.

  • message (bytes) – The message, for the names inside.

  • offset (int) – Offset of data in message.

Return type:

A

Returns:

Parsed RDATA.

Raises:

ProtocolError – If data is not four octets.

_read_rdata_ns(rr_type, data, *, message, offset)[source]

Read an NS RDATA (RFC 1035 Section 3.3.11).

Parameters:
  • rr_type (RRType) – RR type.

  • data (bytes) – RDATA octets.

  • message (bytes) – The message, for the names inside.

  • offset (int) – Offset of data in message.

Return type:

NS

Returns:

Parsed RDATA.

_read_rdata_cname(rr_type, data, *, message, offset)[source]

Read a CNAME RDATA (RFC 1035 Section 3.3.1).

Parameters:
  • rr_type (RRType) – RR type.

  • data (bytes) – RDATA octets.

  • message (bytes) – The message, for the names inside.

  • offset (int) – Offset of data in message.

Return type:

CNAME

Returns:

Parsed RDATA.

_read_rdata_soa(rr_type, data, *, message, offset)[source]

Read an SOA RDATA (RFC 1035 Section 3.3.13).

Parameters:
  • rr_type (RRType) – RR type.

  • data (bytes) – RDATA octets.

  • message (bytes) – The message, for the names inside.

  • offset (int) – Offset of data in message.

Return type:

SOA

Returns:

Parsed RDATA.

Raises:

ProtocolError – If the names do not leave exactly the five 32-bit fields.

_read_rdata_ptr(rr_type, data, *, message, offset)[source]

Read a PTR RDATA (RFC 1035 Section 3.3.12).

Parameters:
  • rr_type (RRType) – RR type.

  • data (bytes) – RDATA octets.

  • message (bytes) – The message, for the names inside.

  • offset (int) – Offset of data in message.

Return type:

PTR

Returns:

Parsed RDATA.

_read_rdata_mx(rr_type, data, *, message, offset)[source]

Read an MX RDATA (RFC 1035 Section 3.3.9).

Parameters:
  • rr_type (RRType) – RR type.

  • data (bytes) – RDATA octets.

  • message (bytes) – The message, for the names inside.

  • offset (int) – Offset of data in message.

Return type:

MX

Returns:

Parsed RDATA.

_read_rdata_txt(rr_type, data, *, message, offset)[source]

Read a TXT RDATA (RFC 1035 Section 3.3.14).

Parameters:
  • rr_type (RRType) – RR type.

  • data (bytes) – RDATA octets.

  • message (bytes) – The message, for the names inside.

  • offset (int) – Offset of data in message.

Return type:

TXT

Returns:

Parsed RDATA.

Raises:

ProtocolError – If data is empty, or a character-string runs past it.

_read_rdata_aaaa(rr_type, data, *, message, offset)[source]

Read an AAAA RDATA (RFC 3596 Section 2.2).

Parameters:
  • rr_type (RRType) – RR type.

  • data (bytes) – RDATA octets.

  • message (bytes) – The message, for the names inside.

  • offset (int) – Offset of data in message.

Return type:

AAAA

Returns:

Parsed RDATA.

Raises:

ProtocolError – If data is not sixteen octets.

_read_rdata_srv(rr_type, data, *, message, offset)[source]

Read an SRV RDATA (RFC 2782).

Parameters:
  • rr_type (RRType) – RR type.

  • data (bytes) – RDATA octets.

  • message (bytes) – The message, for the names inside.

  • offset (int) – Offset of data in message.

Return type:

SRV

Returns:

Parsed RDATA.

_read_rdata_caa(rr_type, data, *, message, offset)[source]

Read a CAA RDATA (RFC 8659 Section 4.1).

Parameters:
  • rr_type (RRType) – RR type.

  • data (bytes) – RDATA octets.

  • message (bytes) – The message, for the names inside.

  • offset (int) – Offset of data in message.

Return type:

CAA

Returns:

Parsed RDATA.

Raises:

ProtocolError – If the tag is empty or runs past data.

_read_opt_unknown(code, data)[source]

Read an EDNS(0) option with no decoder registered: its raw octets.

Parameters:
  • code (Option) – Option code.

  • data (bytes) – OPTION-DATA octets.

Return type:

bytes

Returns:

data itself.

_read_opt_client_subnet(code, data)[source]

Read an edns-client-subnet option (RFC 7871 Section 6).

Parameters:
  • code (Option) – Option code.

  • data (bytes) – OPTION-DATA octets.

Return type:

ClientSubnet

Returns:

Parsed OPTION-DATA.

Read a COOKIE option (RFC 7873 Section 4).

Parameters:
  • code (Option) – Option code.

  • data (bytes) – OPTION-DATA octets.

Return type:

Cookie

Returns:

Parsed OPTION-DATA.

Raises:

ProtocolError – If data is neither the 8-octet client cookie nor that and a server cookie of 8 to 32 octets.

_read_opt_tcp_keepalive(code, data)[source]

Read an edns-tcp-keepalive option (RFC 7828 Section 3.1).

Parameters:
  • code (Option) – Option code.

  • data (bytes) – OPTION-DATA octets.

Return type:

TCPKeepalive

Returns:

Parsed OPTION-DATA.

Raises:

ProtocolError – If data is neither empty nor two octets.

_read_opt_extended_error(code, data)[source]

Read an Extended DNS Error option (RFC 8914 Section 2).

Parameters:
  • code (Option) – Option code.

  • data (bytes) – OPTION-DATA octets.

Return type:

ExtendedError

Returns:

Parsed OPTION-DATA.

_make_rdata_unknown(rr_type, data, *, offset, table)[source]

Make an RDATA with no constructor registered.

Parameters:
  • rr_type (RRType) – RR type.

  • data (Mapping[str, Any]) – RDATA fields; none can be written.

  • offset (int) – Offset of the RDATA in the message.

  • table (dict[tuple[bytes, ...], int] | None) – Names written so far, when compressing.

Return type:

bytes

Returns:

Empty RDATA, for no fields.

Raises:

ProtocolError – If data holds a field.

_make_rdata_a(rr_type, data, *, offset, table)[source]

Make an A RDATA.

Parameters:
Return type:

bytes

Returns:

RDATA octets.

_make_rdata_ns(rr_type, data, *, offset, table)[source]

Make an NS RDATA.

Parameters:
Return type:

bytes

Returns:

RDATA octets.

_make_rdata_cname(rr_type, data, *, offset, table)[source]

Make a CNAME RDATA.

Parameters:
Return type:

bytes

Returns:

RDATA octets.

_make_rdata_soa(rr_type, data, *, offset, table)[source]

Make an SOA RDATA.

Parameters:
  • rr_type (RRType) – RR type.

  • data (Mapping[str, Any]) – RDATA fields, i.e. mname, rname, serial, refresh, retry, expire and minimum.

  • offset (int) – Offset of the RDATA in the message.

  • table (dict[tuple[bytes, ...], int] | None) – Names written so far, when compressing.

Return type:

bytes

Returns:

RDATA octets.

_make_rdata_ptr(rr_type, data, *, offset, table)[source]

Make a PTR RDATA.

Parameters:
  • rr_type (RRType) – RR type.

  • data (Mapping[str, Any]) – RDATA fields, i.e. ptrdname.

  • offset (int) – Offset of the RDATA in the message.

  • table (dict[tuple[bytes, ...], int] | None) – Names written so far, when compressing.

Return type:

bytes

Returns:

RDATA octets.

_make_rdata_mx(rr_type, data, *, offset, table)[source]

Make an MX RDATA.

Parameters:
  • rr_type (RRType) – RR type.

  • data (Mapping[str, Any]) – RDATA fields, i.e. preference and exchange.

  • offset (int) – Offset of the RDATA in the message.

  • table (dict[tuple[bytes, ...], int] | None) – Names written so far, when compressing.

Return type:

bytes

Returns:

RDATA octets.

_make_rdata_txt(rr_type, data, *, offset, table)[source]

Make a TXT RDATA.

Parameters:
Return type:

bytes

Returns:

RDATA octets.

Raises:

ProtocolError – If a string is not bytes of at most 255 octets.

_make_rdata_aaaa(rr_type, data, *, offset, table)[source]

Make an AAAA RDATA.

Parameters:
Return type:

bytes

Returns:

RDATA octets.

_make_rdata_srv(rr_type, data, *, offset, table)[source]

Make an SRV RDATA; its target is never compressed (RFC 2782).

Parameters:
  • rr_type (RRType) – RR type.

  • data (Mapping[str, Any]) – RDATA fields, i.e. priority, weight, port and target.

  • offset (int) – Offset of the RDATA in the message.

  • table (dict[tuple[bytes, ...], int] | None) – Names written so far, when compressing.

Return type:

bytes

Returns:

RDATA octets.

_make_rdata_caa(rr_type, data, *, offset, table)[source]

Make a CAA RDATA.

Parameters:
  • rr_type (RRType) – RR type.

  • data (Mapping[str, Any]) – RDATA fields, i.e. flags, tag and value; the Issuer Critical flag is the high bit of flags.

  • offset (int) – Offset of the RDATA in the message.

  • table (dict[tuple[bytes, ...], int] | None) – Names written so far, when compressing.

Return type:

bytes

Returns:

RDATA octets.

Raises:

ProtocolError – If tag is not bytes of 1 to 255 octets, or value is not bytes.

_make_opt_unknown(code, data)[source]

Make an EDNS(0) option with no constructor registered.

Parameters:
  • code (Option) – Option code.

  • data (Mapping[str, Any]) – OPTION-DATA fields; none can be written.

Return type:

bytes

Returns:

Empty OPTION-DATA, for no fields.

Raises:

ProtocolError – If data holds a field.

_make_opt_client_subnet(code, data)[source]

Make an edns-client-subnet option.

Parameters:
  • code (Option) – Option code.

  • data (Mapping[str, Any]) – OPTION-DATA fields, i.e. family, source_prefix, scope_prefix and address.

Return type:

bytes

Returns:

OPTION-DATA octets.

Raises:

ProtocolError – If address is not bytes.

Make a COOKIE option.

Parameters:
  • code (Option) – Option code.

  • data (Mapping[str, Any]) – OPTION-DATA fields, i.e. client and server.

Return type:

bytes

Returns:

OPTION-DATA octets.

Raises:

ProtocolError – If client is not 8 octets, or server is neither empty nor of 8 to 32 octets.

_make_opt_tcp_keepalive(code, data)[source]

Make an edns-tcp-keepalive option.

Parameters:
  • code (Option) – Option code.

  • data (Mapping[str, Any]) – OPTION-DATA fields, i.e. timeout, which None leaves out.

Return type:

bytes

Returns:

OPTION-DATA octets.

_make_opt_extended_error(code, data)[source]

Make an Extended DNS Error option.

Parameters:
  • code (Option) – Option code.

  • data (Mapping[str, Any]) – OPTION-DATA fields, i.e. info_code and extra_text.

Return type:

bytes

Returns:

OPTION-DATA octets.

Raises:

ProtocolError – If extra_text is not bytes.

_read_dns_name(message, pos, *, limit=None)[source]

Read a domain name, following its compression pointers.

Parameters:
  • message (bytes) – The message, from its header on.

  • pos (int) – Offset of the name in message.

  • limit (int | None) – Offset the name has to end by, if any.

Return type:

tuple[Name, int]

Returns:

The name, and the offset just past it.

Raises:

ProtocolError – As read_name() raises it, or if the name ends past limit.

_read_rdata_name(data, message, offset, *, skip=0)[source]

Read the domain name that ends an RDATA.

Parameters:
  • data (bytes) – RDATA octets.

  • message (bytes) – The message, from its header on.

  • offset (int) – Offset of data in message.

  • skip (int) – Octets of data before the name.

Return type:

Name

Returns:

The name.

Raises:

ProtocolError – If the name does not end where data does.

_make_dns_name(name, *, offset, table)[source]

Make a domain name.

Parameters:
  • name (str | Iterable[bytes] | Mapping[str, Any]) – A Name, or its dict form, written with the compression it records; or its labels, or its presentation form, compressed against table if given.

  • offset (int) – Offset of the name in the message.

  • table (dict[tuple[bytes, ...], int] | None) – Names written so far, when compressing; the suffixes this name writes in full are added to it.

Return type:

bytes

Returns:

The name’s octets.

Raises:

ProtocolError – If name is none of those, or is malformed.

_read_dns_opt(name, udp_payload_size, ttl, rdata)[source]

Read the OPT pseudo-record of EDNS(0).

Structure of the OPT record’s TTL field [RFC 6891 Section 6.1.3]:

              +0 (MSB)                            +1 (LSB)
   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
0: |         EXTENDED-RCODE        |            VERSION            |
   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
2: | DO|                           Z                               |
   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
Parameters:
  • name (Name) – Owner name.

  • udp_payload_size (int) – The CLASS field.

  • ttl (int) – The TTL field.

  • rdata (bytes) – RDATA octets, i.e. the options.

Return type:

OPT

Returns:

The record; its options are the raw RDATA where their framing does not decode.

_make_dns_opt(record)[source]

Make the CLASS, TTL and RDATA fields of the OPT pseudo-record.

Parameters:

record (Mapping[str, Any]) – The fields of OPT.

Return type:

tuple[int, int, bytes]

Returns:

The CLASS and TTL values, and the RDATA octets.

_read_dns_options(data)[source]

Read the options of the OPT pseudo-record.

Structure of an option [RFC 6891 Section 6.1.2]:

              +0 (MSB)                            +1 (LSB)
   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
0: |                          OPTION-CODE                          |
   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
2: |                         OPTION-LENGTH                         |
   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
4: |                                                               |
   /                          OPTION-DATA                          /
   /                                                               /
   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

Each OPTION-DATA is read by the parser __option__ registers for its code, and kept as raw octets where that parser rejects it.

Parameters:

data (bytes) – The OPT record’s RDATA.

Return type:

tuple[Option, ...]

Returns:

The options, in order.

Raises:

ProtocolError – If an option’s header or data runs past data.

_make_dns_options(options)[source]

Make the options of the OPT pseudo-record.

Parameters:

options (Iterable[Mapping[str, Any]]) – Each option’s code, length and data, as Option holds them; data is raw octets or a mapping of the fields of the code’s data model, and length is computed when not given.

Return type:

bytes

Returns:

The options’ octets.

_import_next_layer(proto, length=None, *, packet=None)[source]

Import next layer extractor: a further whole message, or the rest undissected.

Over TCP, a segment may carry several messages, each behind its length field. So the -1 remainder after a framed message is dissected as this class when _opens_whole_message() finds a whole message opening it, and is otherwise kept as Application._import_next_layer keeps it.

Parameters:
  • proto (int) – next layer protocol index; only the -1 sentinel (the rest) is accepted

  • length (int | None) – valid (non-padding) length

  • packet (dict[str, Any] | None) – packet info (passed from self.unpack)

Return type:

ProtocolBase

Returns:

Instance of this class for a further message, or as Application._import_next_layer returns otherwise.

_import_next_message(proto, length=None, *, packet=None)[source]

Import the further message _import_next_layer() found.

Parameters:
  • proto (int) – next layer protocol index, the -1 sentinel

  • length (int | None) – valid (non-padding) length

  • packet (dict[str, Any] | None) – packet info (passed from self.unpack)

Return type:

ProtocolBase

Returns:

Instance of this class, or of Raw when beholder() replaces a message that fails to parse.

Auxiliary Functions

pcapkit.protocols.application.dns.protocol._opens_whole_message(octets)[source]

Whether octets open with a whole message behind a TCP length field.

Parameters:

octets (bytes) – Octets after a message over TCP.

Return type:

bool

Returns:

Whether the two-octet length is at least a header’s and the octets it counts are all there.

pcapkit.protocols.application.dns.protocol._sections_end(message)[source]

Where the sections the header of message counts end, if they fit in it.

Parameters:

message (bytes) – Octets read as a message, from its header on.

Return type:

int | None

Returns:

The offset just past the last entry, where every entry the four counts name has a well-formed name and ends inside message; None otherwise. RDATA is not decoded.

pcapkit.protocols.application.dns.protocol._frames_message(octets)[source]

Whether octets are a message behind the TCP length field.

Parameters:

octets (bytes) – Octets of a DNS layer, with framed not given.

Return type:

bool

Returns:

Whether a whole message behind a length field opens octets and decodes, and octets do not decode as a message, or decode no better. Where both readings decode and the framed message ends exactly at its length, the framed one is taken if the plain one stops short of the end of octets; if it reads to the end, the framed one is taken where it counts a question and the plain one none, or where a further framed message follows that ends exactly at its length too. So a plain message whose ID equals the octets after it, with its question, stays plain.

Note

A length read as an ID makes the flags read as the question count, which flags of zero leave at zero, so the plain reading of a framed message with such flags can decode: it stops short of the end, or reads an octet run it lands on, such as a following message’s length, as an RDLENGTH counting the rest.

Header Schemas

class pcapkit.protocols.application.dns.schema.DNS(length=NO_VALUE, id=NO_VALUE, flags=NO_VALUE, qdcount=NO_VALUE, ancount=NO_VALUE, nscount=NO_VALUE, arcount=NO_VALUE, body=NO_VALUE, payload=NO_VALUE, *, __packet__=None, **kwargs)[source]

Bases: Schema

Header schema for DNS message.

The two-octet length precedes the message over TCP alone (RFC 1035 Section 4.2.2), which __framed__ in the packet context says when unpacking; packing, a length given says it.

length: int | None = <ConditionalField length>

Message length, over TCP.

id: int = <UInt16Field id>

Identifier.

flags: Flags = <BitField flags>

Flags.

qdcount: int = <UInt16Field qdcount>

Number of question entries.

ancount: int = <UInt16Field ancount>

Number of answer records.

nscount: int = <UInt16Field nscount>

Number of authority records.

arcount: int = <UInt16Field arcount>

Number of additional records.

body: bytes = <BytesField body>

The four sections, undecoded.

payload: bytes = <PayloadField payload>

Octets after the message, e.g. a further message over TCP.

classmethod pre_unpack(packet)[source]

Prepare packet data for unpacking process.

Parameters:

packet (dict[str, Any]) – packet data

pre_pack(packet)[source]

Prepare packet data for packing process.

Parameters:

packet (dict[str, Any]) – packet data

Type Stubs

class pcapkit.protocols.application.dns.schema.Flags[source]

Bases: TypedDict

DNS header flags.

qr: int

Query or response.

opcode: int

Kind of query.

aa: int

Authoritative answer.

tc: int

Truncation.

rd: int

Recursion desired.

ra: int

Recursion available.

z: int

Reserved bit.

ad: int

Authentic data.

cd: int

Checking disabled.

rcode: int

Response code.

Domain Name Codec

The codec works on octets and labels, with no protocol state, so another protocol carrying domain names can call it.

pcapkit.protocols.application.dns.schema.read_name(data, pos, *, compression=True, alias='DNS')[source]

Read the domain name at pos in data.

Parameters:
  • data (bytes) – The octets compression pointers are offsets into, i.e. the whole DNS message for DNS.

  • pos (int) – Offset of the name in data.

  • compression (bool) – Whether a compression pointer may end the name.

  • alias (str) – Prefix of the error message.

Return type:

tuple[tuple[bytes, ...], int, int | None, int]

Returns:

Every label of the name, the root’s left out; how many of them are written in full at pos; the offset the pointer ending the name there points to, or None where the root label ends it; and the offset just past the name at pos.

Raises:

ProtocolError – If the name runs past the end of data, holds a label type other than a plain label or, where compression allows one, a pointer (RFC 6891 Section 5), or its pointers loop.

pcapkit.protocols.application.dns.schema.make_name(labels, *, literal=None, pointer=None, alias='DNS')[source]

Write a domain name, the inverse of read_name().

Parameters:
  • labels (Sequence[bytes]) – Every label of the name, the root’s left out.

  • literal (int | None) – How many of labels to write in full; all of them if None.

  • pointer (int | None) – Offset a compression pointer after them points to, or None to end the name with the root label.

  • alias (str) – Prefix of the error message.

Return type:

bytes

Returns:

The name’s octets.

Raises:

ProtocolError – If a label written is empty or longer than 63 octets, literal is not a count of labels, or pointer does not fit in 14 bits.

pcapkit.protocols.application.dns.schema.compress_name(labels, table, offset)[source]

Choose how to write a name against the names already written.

Parameters:
  • labels (Sequence[bytes]) – Every label of the name, the root’s left out.

  • table (dict[tuple[bytes, ...], int]) – Each label suffix already written, by its offset; the suffixes this name writes in full are added to it.

  • offset (int) – Offset the name is written at.

Returns:

the longest suffix in table is pointed to, and the labels before it written.

Return type:

tuple[int, int | None]

pcapkit.protocols.application.dns.schema.record_name(labels, literal, table, offset)[source]

Add the label suffixes a name writes in full to table.

Parameters:
  • labels (Sequence[bytes]) – Every label of the name, the root’s left out.

  • literal (int) – How many of labels the name writes in full.

  • table (dict[tuple[bytes, ...], int]) – Each label suffix already written, by its offset.

  • offset (int) – Offset the name is written at.

pcapkit.protocols.application.dns.schema.name_to_text(labels)[source]

Render labels in presentation form (RFC 1035 Section 5.1).

Parameters:

labels (Sequence[bytes]) – Every label of the name, the root’s left out.

Return type:

str

Returns:

The absolute name, e.g. www.example.com., with . and \ escaped by a backslash, and any octet outside printable ASCII or a space as \DDD; the root is ..

pcapkit.protocols.application.dns.schema.text_to_labels(text, *, alias='DNS')[source]

Read a name in presentation form into labels, the inverse of name_to_text().

Parameters:
  • text (str) – The name; the trailing . is optional, and '' or . is the root.

  • alias (str) – Prefix of the error message.

Return type:

tuple[bytes, ...]

Returns:

Every label of the name, the root’s left out.

Raises:

ProtocolError – If text holds an empty label, or a backslash not followed by a character or by three decimal digits up to 255.

pcapkit.protocols.application.dns.schema.dns_body_length(pkt)[source]

Length of DNS.body.

Parameters:

pkt (dict[str, Any]) – Packet data.

Return type:

int

Returns:

Over TCP, the message length the prefix gives less the header; else the rest of the data. Packing, where __length__ is unset, the body as given.

Data Models

class pcapkit.protocols.application.dns.data.DNS(id, flags, qdcount, ancount, nscount, arcount, question, answer, authority, additional)[source]

Bases: Protocol

Data model for a DNS message (RFC 1035 Section 4.1).

id: int

Identifier.

flags: Flags

Header flags.

qdcount: int

Number of question entries, as the header gives it.

ancount: int

Number of answer records, as the header gives it.

nscount: int

Number of authority records, as the header gives it.

arcount: int

Number of additional records, as the header gives it.

question: tuple[Question, ...]

Question section.

answer: tuple[ResourceRecord | OPT, ...]

Answer section.

authority: tuple[ResourceRecord | OPT, ...]

Authority section.

additional: tuple[ResourceRecord | OPT, ...]

Additional section, holding the OPT pseudo-record of EDNS(0) if any.

length: int

Message length, the two-octet field preceding the message over TCP (RFC 1035 Section 4.2.2); present only for such a message.

trailer: bytes

Octets of the message past its last record, present only when there are any.

class pcapkit.protocols.application.dns.data.Flags(qr, opcode, aa, tc, rd, ra, z, ad, cd, rcode)[source]

Bases: Data

Data model for the DNS header flags (RFC 1035 Section 4.1.1).

qr: bool

Whether the message is a response.

opcode: Opcode

Kind of query.

aa: bool

Authoritative answer.

tc: bool

Truncation.

rd: bool

Recursion desired.

ra: bool

Recursion available.

z: int

Reserved bit.

ad: bool

Authentic data (RFC 4035 Section 3.2.3).

cd: bool

Checking disabled (RFC 4035 Section 3.2.2).

rcode: RCode

Response code, the low four bits of an extended one (RFC 6891 Section 6.1.3).

class pcapkit.protocols.application.dns.data.Name(name, labels, literal, pointer)[source]

Bases: Data

Data model for a domain name (RFC 1035 Section 3.1).

literal and pointer record how the name was written, so that it is rebuilt with the compression it was read with (RFC 1035 Section 4.1.4).

name: str

Name in presentation form, absolute, e.g. www.example.com.; the root is ..

labels: tuple[bytes, ...]

Every label of the name, the root’s empty label left out.

literal: int

How many of labels are written in full where the name is.

pointer: int | None

Offset into the message of the compression pointer ending the name, or None where the root label ends it.

class pcapkit.protocols.application.dns.data.Question(name, type)[source]

Bases: Data

Data model for a question section entry (RFC 1035 Section 4.1.2).

Its class key, a keyword in Python, holds the RRClass.

name: Name

Domain name asked about.

type: RRType

Type of the query.

class pcapkit.protocols.application.dns.data.ResourceRecord(name, type, ttl, rdlength, rdata)[source]

Bases: Data

Data model for a resource record (RFC 1035 Section 4.1.3).

Its class key, a keyword in Python, holds the RRClass. rdata holds the decoded RDATA where DNS.__rdata__ registers a decoder for type, and the raw octets otherwise, including RDATA its decoder cannot read exactly.

name: Name

Owner name.

type: RRType

Type.

ttl: int

Time to live, in seconds.

rdlength: int

Length of the RDATA.

rdata: RData | bytes

RDATA, decoded or as raw octets.

class pcapkit.protocols.application.dns.data.OPT(name, type, udp_payload_size, extended_rcode, version, do, z, rdlength, options)[source]

Bases: Data

Data model for the OPT pseudo-record of EDNS(0) (RFC 6891 Section 6.1.2).

The CLASS and TTL fields of a resource record are redefined for it, and each of their parts has a field here.

name: Name

Owner name, the root.

type: RRType

Type, OPT.

udp_payload_size: int

Requestor’s UDP payload size, the CLASS field.

extended_rcode: int

Upper eight bits of the extended RCODE.

version: int

EDNS version.

do: bool

DNSSEC OK bit (RFC 3225 Section 3).

z: int

The remaining fifteen bits of the TTL field.

rdlength: int

Length of the RDATA.

options: tuple[Option, ...] | bytes

Options, or the raw RDATA where they do not decode.

class pcapkit.protocols.application.dns.data.Option(code, length, data)[source]

Bases: Data

Data model for an EDNS(0) option (RFC 6891 Section 6.1.2).

data holds the decoded OPTION-DATA where DNS.__option__ registers a decoder for code, and the raw octets otherwise.

code: Option

OPTION-CODE.

length: int

OPTION-LENGTH.

data: OptionData | bytes

OPTION-DATA, decoded or as raw octets.

RDATA

class pcapkit.protocols.application.dns.data.RData(*args, **kwargs)[source]

Bases: Data

Data model for the decoded RDATA of a resource record.

Each subclass is the structure one RRType carries, its fields named as its specification names them.

class pcapkit.protocols.application.dns.data.A(address)[source]

Bases: RData

Data model for the A RDATA (RFC 1035 Section 3.4.1).

address: IPv4Address

IPv4 address.

class pcapkit.protocols.application.dns.data.NS(nsdname)[source]

Bases: RData

Data model for the NS RDATA (RFC 1035 Section 3.3.11).

nsdname: Name

Authoritative name server.

class pcapkit.protocols.application.dns.data.CNAME(cname)[source]

Bases: RData

Data model for the CNAME RDATA (RFC 1035 Section 3.3.1).

cname: Name

Canonical name.

class pcapkit.protocols.application.dns.data.SOA(mname, rname, serial, refresh, retry, expire, minimum)[source]

Bases: RData

Data model for the SOA RDATA (RFC 1035 Section 3.3.13).

mname: Name

Primary name server of the zone.

rname: Name

Mailbox of the person responsible for the zone.

serial: int

Version number of the zone.

refresh: int

Refresh interval, in seconds.

retry: int

Retry interval, in seconds.

expire: int

Expiry limit, in seconds.

minimum: int

Minimum TTL, in seconds; the negative-caching TTL (RFC 2308 Section 4).

class pcapkit.protocols.application.dns.data.PTR(ptrdname)[source]

Bases: RData

Data model for the PTR RDATA (RFC 1035 Section 3.3.12).

ptrdname: Name

Name pointed to.

class pcapkit.protocols.application.dns.data.MX(preference, exchange)[source]

Bases: RData

Data model for the MX RDATA (RFC 1035 Section 3.3.9).

preference: int

Preference, lower preferred.

exchange: Name

Mail exchange host.

class pcapkit.protocols.application.dns.data.TXT(strings)[source]

Bases: RData

Data model for the TXT RDATA (RFC 1035 Section 3.3.14).

strings: tuple[bytes, ...]

The character-strings, each without its length octet.

class pcapkit.protocols.application.dns.data.AAAA(address)[source]

Bases: RData

Data model for the AAAA RDATA (RFC 3596 Section 2.2).

address: IPv6Address

IPv6 address.

class pcapkit.protocols.application.dns.data.SRV(priority, weight, port, target)[source]

Bases: RData

Data model for the SRV RDATA (RFC 2782).

priority: int

Priority, lower preferred.

weight: int

Weight among targets of equal priority.

port: int

Port of the service.

target: Name

Target host.

class pcapkit.protocols.application.dns.data.CAA(flags, critical, tag, value)[source]

Bases: RData

Data model for the CAA RDATA (RFC 8659 Section 4.1).

flags: int

Flags octet.

critical: bool

Issuer Critical flag, the flags octet’s high bit.

tag: bytes

Property tag.

value: bytes

Property value.

EDNS(0) Options

class pcapkit.protocols.application.dns.data.OptionData(*args, **kwargs)[source]

Bases: Data

Data model for the decoded OPTION-DATA of an EDNS(0) option.

Each subclass is the structure one Option carries, its fields named as its specification names them.

class pcapkit.protocols.application.dns.data.ClientSubnet(family, source_prefix, scope_prefix, address)[source]

Bases: OptionData

Data model for the edns-client-subnet option (RFC 7871 Section 6).

family: int

Address family (IANA Address Family Numbers).

source_prefix: int

Source prefix length.

scope_prefix: int

Scope prefix length.

address: bytes

Address, as many octets as source_prefix covers.

class pcapkit.protocols.application.dns.data.Cookie(client, server)[source]

Bases: OptionData

Data model for the COOKIE option (RFC 7873 Section 4).

client: bytes

Client cookie.

server: bytes

Server cookie, empty when absent.

class pcapkit.protocols.application.dns.data.TCPKeepalive(timeout)[source]

Bases: OptionData

Data model for the edns-tcp-keepalive option (RFC 7828 Section 3.1).

timeout: int | None

Idle timeout, in units of 100 milliseconds, or None when absent.

class pcapkit.protocols.application.dns.data.ExtendedError(info_code, extra_text)[source]

Bases: OptionData

Data model for the Extended DNS Error option (RFC 8914 Section 2).

info_code: int

INFO-CODE.

extra_text: bytes

EXTRA-TEXT, as octets; UTF-8 by the specification.

Constants

pcapkit.protocols.application.dns.const.HEADER_LENGTH = 12

Length of the fixed header, before the sections (RFC 1035 Section 4.1.1).

pcapkit.protocols.application.dns.const.POINTER_LIMIT = 16383

Largest offset a compression pointer can carry, in its 14 bits.