Something went wrong. Try again.
DNS message encoding and decoding for Zig, with no I/O and no allocation.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326#!/usr/bin/env python3# SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us># SPDX-License-Identifier: MIT
"""Compare this library's decoder against dnspython's.
Everything in `tests/fuzz.zig` is this library agreeing with itself: it catchesa decoder and an encoder that have drifted apart, and cannot catch both of thembeing wrong the same way. The check for that is to put the same bytes to adecoder somebody else wrote.
The bytes are mutations of the messages in `tests/corpus.zig`, which`tools/verdict.zig` hands over in hex so that there is only ever one copy of apacket capture. Each side is asked two things: whether the message is wellformed, and how many questions and records it found. A disagreement is either abug or a deliberate difference in strictness, and the ones that are deliberateare written down in EXPECTED below -- so a new kind of disagreement fails therun and a known one does not.
Run it from inside `nix develop`, which is where dnspython comes from:
zig build differential zig build differential -- --count 200000 --seed 7"""
import argparseimport collectionsimport osimport randomimport subprocessimport sysimport tempfile
import dns.message
# The disagreements that are choices rather than defects, each with the reason# it is one. A class not in here fails the run, which is the whole mechanism:# a new kind of disagreement has to be looked at and then either fixed or# written down here, and nothing else about the run can drift.## "mine" is this library and "theirs" is dnspython. The key is which side# refused the message and what it said. Nine of these turn up in a run of a# couple of hundred thousand messages; the other two are error paths this# library has that a different corpus would reach.EXPECTED = { ("mine", "Truncated"): ( "a record whose length does not reach the end of a field its type " "requires -- an AAAA with no address, a name cut in half. dnspython " "keeps such a record as opaque data instead; RFC 3597 says to do that " "for a type you do not know, not for one you do" ), ("mine", "TrailingRdata"): ( "a record longer than its type needs, such as an MD holding a root " "name and then two more bytes. The length field and the type have to " "agree and there is no way to tell which to believe" ), ("mine", "MalformedRdata"): ( "record data that is the wrong shape for its type: SVCB parameters " "out of order or claiming more bytes than the record holds, an NSEC " "type bitmap with a window longer than 32 bytes" ), ("mine", "ReservedLabelType"): ( "a name inside record data whose length byte has the top two bits set " "to 01 or 10. RFC 1035 reserved both and nothing has ever defined " "either, so the only thing that produces one is a corrupt message" ), ("mine", "BadPointer"): ( "a compression pointer inside record data that points at itself or " "forwards. Requiring backwards is what makes a walk terminate" ), ("mine", "NameTooLong"): ( "a name that expands past 255 bytes, which is usually a pointer cycle " "rather than a long name" ), ("mine", "QuestionOnlyType"): ( "a record whose type is one that is only ever a question -- ANY, " "AXFR, IXFR, MAILA, MAILB. There is no such record, so there is " "nothing for `data` to decode and it says so. dnspython registers " "them as records with no data at all and accepts one; the bytes are " "still on Record.rdata here for anything that only wants to forward " "them" ), ("mine", "TrailingBytes"): ( "bytes after the last section. dnspython was asked not to ignore " "trailing data either, so this one is usually a count that disagrees " "with what follows in a way only one side noticed" ), ("theirs", "FormError"): ( "types this library does not parse and dnspython does -- LOC with a " "latitude out of range, ZONEMD, DSYNC -- which RFC 3597 says to carry " "as opaque data; and dnspython imposing the zone/prerequisite/update " "structure of RFC 2136 on any message whose opcode is UPDATE, which " "this library deliberately does not" ), ("theirs", "BadLabelType"): ( "the same reserved label types, found by dnspython inside a record " "type it parses and this library does not" ), ("theirs", "BadPointer"): ( "two different causes. One is the rule: dnspython requires each " "pointer target to be below the last one followed, and this library " "by default requires only that a pointer point below itself -- pass " "--strict-pointers to ask the same question dnspython asks, and those " "cases go away. The other survives that, and is a bad pointer inside " "the data of a record type dnspython parses and this library carries " "through as unknown, where there is no name for either rule to judge" ), ("theirs", "BadEDNS"): ( "an EDNS rule this library does not impose: dnspython refuses a " "version it does not know, and a second OPT record wherever it is, " "while Message.opt refuses a second one and carries any version" ), ("theirs", "BadTSIG"): ( "dnspython resuming a record header in the wrong place. Its name " "parser leaves the parser at the furthest byte it touched, which for " "a pointer whose target is a run of bytes extending past the pointer " "is past the pointer itself -- so it reads the type from there, finds " "250, and refuses a TSIG outside the additional section. This library " "reads such a name as the two bytes of the pointer, and the record " "then frames exactly to the end of the message. Nothing that " "compresses a name can produce such a pointer" ), ("counts", "dnspython merged records this library counted separately"): ( "dnspython groups records into RRsets and drops a duplicate within " "one, so a mutation that makes two records identical loses one on " "that side. This library counts what arrived, duplicates and all" ),}
# The bytes a DNS message is mostly made of. Zero because it ends every name,# 0xc0..0xc3 because they begin a compression pointer and turning a label# length into a pointer is the single most productive mutation there is, 0x40# and 0x80 because they are the reserved label types, and the small numbers# because they are label lengths, type numbers and counts.INTERESTING = bytes( [0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC1, 0xC2, 0xC3, 0xFF, 0x40, 0x80, 0x3F] + [1, 2, 3, 4, 5, 6, 0x0C, 0x0F, 0x10, 0x1C, 0x29, 0x2E, 0x2F, 0x30, 0x41])
def mutate(message, rng): out = bytearray(message) for _ in range(1 + rng.randrange(8)): if not out: out.append(rng.randrange(256)) continue op = rng.randrange(8) i = rng.randrange(len(out)) if op < 3: out[i] = rng.randrange(256) elif op < 6: out[i] = rng.choice(INTERESTING) elif op == 6: out.insert(i, rng.choice(INTERESTING)) else: del out[i] return bytes(out)
def theirs(raw): """dnspython's verdict, in the same shape the Zig tool prints.""" try: message = dns.message.from_wire(raw, ignore_trailing=False) except Exception as error: # noqa: BLE001 - any failure is a refusal return "ERR " + type(error).__name__ # dnspython lifts the OPT record out of the additional section rather than # counting it as a record, which is why the Zig side does not count it # either. records = sum( len(rrset) for section in (message.answer, message.authority, message.additional) for rrset in section ) return "OK %d %d" % (len(message.question), records)
def _counts_class(ours, theirs_said): """Name the way two accepted verdicts disagree about what is in a message.
The one difference that is not a defect is dnspython having merged records this library counted separately, which can only ever make its count lower. Anything else -- a different number of questions, or more records on that side than this one -- is one of the two having read the message wrongly. """ _, our_questions, our_records = ours.split() _, their_questions, their_records = theirs_said.split() if our_questions == their_questions and int(their_records) < int(our_records): return ("counts", "dnspython merged records this library counted separately") return ("counts", "%s vs %s" % (ours, theirs_said))
def run(argv): """The verdict tool's stdout, or the reason it did not produce any.
Its stderr has to be repeated here, because a `check=True` that captured it raises with the message thrown away: a tool that said `error: StreamTooLong` and stopped showed up as a Python traceback about an exit status, and the sentence that would have explained it was the one being discarded. """ done = subprocess.run(argv, capture_output=True, text=True) if done.returncode != 0: sys.exit( "%s exited %d\n%s" % (" ".join(argv), done.returncode, done.stderr.strip() or "(said nothing)") ) return done.stdout
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("verdict", help="the tools/verdict.zig binary") # Thirty seconds or so, which is short enough for every push and long # enough that eleven of the classes in EXPECTED turn up in it. The rest are # rarer than that: `theirs BadTSIG` took a million messages to appear once, # which is why the count is worth turning up by hand from time to time. parser.add_argument("--count", type=int, default=200000) parser.add_argument("--seed", type=int, default=1) parser.add_argument( "--show", type=int, default=1, help="how many example messages to print per class of disagreement", ) parser.add_argument( "--strict-pointers", action="store_true", help=( "decode with Name.PointerRule.descending, which is the rule " "dnspython uses: the disagreement about compression pointers must " "then not happen at all, and the run fails if it does" ), ) options = parser.parse_args()
flags = ["--strict-pointers"] if options.strict_pointers else [] corpus = [bytes.fromhex(line) for line in run([options.verdict, "--corpus"]).split()] if not corpus: sys.exit("the verdict tool gave back no corpus")
rng = random.Random(options.seed) cases = [mutate(rng.choice(corpus), rng) for _ in range(options.count)]
with tempfile.TemporaryDirectory() as directory: path = os.path.join(directory, "cases.hex") with open(path, "w") as handle: handle.write("".join(case.hex() + "\n" for case in cases)) mine = run([options.verdict, *flags, path]).splitlines()
if len(mine) != len(cases): sys.exit("got %d verdicts for %d messages" % (len(mine), len(cases)))
both_ok = both_err = 0 classes = collections.defaultdict(list) for raw, ours in zip(cases, mine): theirs_said = theirs(raw) we_accept = ours.startswith("OK") they_accept = theirs_said.startswith("OK") if we_accept and they_accept: both_ok += 1 if ours != theirs_said: classes[_counts_class(ours, theirs_said)].append(raw) elif we_accept: classes[("theirs", theirs_said.split()[1])].append(raw) elif they_accept: classes[("mine", ours.split()[1])].append(raw) else: both_err += 1
print( "%d messages from seed %d%s: both accept %d, both refuse %d, disagree %d" % ( options.count, options.seed, ", strict pointers" if options.strict_pointers else "", both_ok, both_err, sum(len(v) for v in classes.values()), ) )
expected = EXPECTED unexpected = [] for key in sorted(classes, key=lambda k: -len(classes[k])): examples = classes[key] side, what = key known = expected.get(key) print() print( " %-5s %-20s %6d %s" % (side, what, len(examples), "expected" if known else "*** NOT EXPECTED") ) if known: for line in _wrap(known): print(" " + line) else: unexpected.append(key) for example in examples[: options.show]: print(" e.g. " + example.hex())
if unexpected: print() print("%d kind(s) of disagreement are not accounted for." % len(unexpected)) print("Each is either a bug or a strictness choice to write into EXPECTED.") return 1
print() print("Every disagreement is one that is written down.") return 0
def _wrap(text, width=66): line, lines = "", [] for word in text.split(): if len(line) + len(word) + 1 > width: lines.append(line) line = word else: line = (line + " " + word).strip() if line: lines.append(line) return lines
if __name__ == "__main__": sys.exit(main())