Something went wrong. Try again.
DNS message encoding and decoding for Zig, with no I/O and no allocation.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433#!/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 tempfileimport traceback
import dns.exceptionimport 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 why, which for dnspython is what `_refusal` makes of# the exception. Most of these turn up in a run of a couple of hundred# thousand messages; the rest are rarer, or are error paths 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, claiming more bytes than the record holds, or holding " "a value the wrong shape for its key; an NSEC type bitmap with a " "window longer than 32 bytes. Often in a record whose class is not " "IN, which dnspython carries as opaque for types it parses only " "there, and this library decodes by type whatever the class" ), ("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 that leads to another pointer, or to a name " "that does not end before the stretch of name holding the pointer " "began (docs/adr/0002). dnspython follows up to sixteen pointers in a " "row, and does not read names at all inside some record types this " "library does" ), ("mine", "NameTooLong"): ( "a name that expands past 255 bytes, which is usually a pointer cycle " "rather than a long name" ), ("mine", "RecordlessType"): ( "a record whose type is one that never has record data -- ANY, " "AXFR, IXFR, MAILA, MAILB, NXNAME. 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 in update._parse_rr_header"): ( "dnspython imposing the zone/prerequisite/update structure of RFC " "2136 on any message whose opcode is UPDATE, which this library " "deliberately does not" ), ("theirs", "FormError in svcbbase"): ( "a value for SVCB key 10, docpath (DNS over CoAP), that is the wrong " "shape. dnspython knows the key; this library carries it as an " "unknown one, with whatever it holds" ), ("theirs", "FormError: parameters in AliasMode"): ( "an SVCB or HTTPS record in alias mode that carries parameters. RFC " "9460 section 2.4.2 says a recipient must ignore them, not that the " "record is malformed, so this library carries them through" ), ("theirs", "FormError: fingerprint length inconsistent with fingerprint type"): ( "an SSHFP whose fingerprint is not the length its fingerprint type " "implies. Which lengths go with which type is a registry's business " "and a new type can change it, so this library carries it " "(docs/adr/0001)" ), ("mine", "CompressionForbidden"): ( "a compressed name where its type forbids one, in a record dnspython " "does not read the name of: an SVCB, HTTPS or other type it parses " "only in class IN, carried as opaque data in any other class. This " "library decodes record data by type, whatever the class" ), ("theirs", "FormError: digest length inconsistent with digest type"): ( "a DS, DLV or TA whose digest is not the length its digest type " "implies -- the same kind of meaning rule as SSHFP's, carried for the " "same reason (docs/adr/0001)" ), ("theirs", "FormError: digest type 0 is reserved"): ( "a DS whose digest type is the reserved 0. CDS uses 0 to ask for " "deletion (RFC 8078), which shows how a reserved number comes to mean " "something, so this library carries it (docs/adr/0001)" ), ( "theirs", "FormError: certificate association data length inconsistent with " "matching type", ): ( "a TLSA or SMIMEA whose data is not the length its matching type " "implies -- the same kind of meaning rule as SSHFP's, carried for the " "same reason (docs/adr/0001)" ), ("theirs", "FormError: bad size: non-canonical zero"): ( "a LOC size of a zero base with a nonzero exponent, which is zero " "written in a way nothing produces. It is still zero, so this library " "carries it and prints it as 0.00m" ), ("theirs", "FormError: bad horizontal precision: non-canonical zero"): ( "a LOC horizontal precision of a zero base with a nonzero exponent, which is zero " "written in a way nothing produces. It is still zero, so this library " "carries it and prints it as 0.00m" ), ("theirs", "FormError: bad vertical precision: non-canonical zero"): ( "a LOC vertical precision of a zero base with a nonzero exponent, which is zero " "written in a way nothing produces. It is still zero, so this library " "carries it and prints it as 0.00m" ), ("theirs", "FormError: bad latitude"): ( "a LOC latitude past a pole. A number that is not a place is a question of " "meaning, as GPOS's are, so this library carries it" ), ("theirs", "FormError: bad longitude"): ( "a LOC longitude past the antimeridian. A number that is not a place is a question of " "meaning, as GPOS's are, so this library carries it" ), ("theirs", "FormError: hash_algorithm 0 is reserved"): ( "a ZONEMD whose hash algorithm is the reserved 0. Which numbers are " "reserved is a registry's business and can change, so this library " "carries it (docs/adr/0001)" ), ("theirs", "FormError: scheme 0 is reserved"): ( "a ZONEMD whose scheme is the reserved 0, carried for the same reason " "as its hash algorithm" ), ("theirs", "BadLabelType"): ( "the same reserved label types, found by dnspython inside a record " "type it parses and this library does not" ), ("theirs", "BadPointer"): ( "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 " "this library to judge" ), ("theirs", "PointerChainTooLong"): ( "a name that follows more than sixteen pointers, each one to a label. " "dnspython stops at sixteen; here the 255-byte limit on a name is what " "bounds the count, since a legitimate name of seventeen labels can " "need seventeen (docs/adr/0002)" ), ("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" ), ("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 " + _refusal(error) # 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 _refusal(error): """Name why dnspython refused a message, finely enough to tell causes apart.
dnspython's specific exceptions -- `BadPointer`, `BadEDNS` and the rest -- are each raised from one place and say enough by their class. A plain `FormError` is raised from everywhere, usually without a message, so the class alone lumps together a TLSA whose digest is the wrong length and an UPDATE whose prerequisites are out of place; once one of those is written down, every other cause would be accepted with it. So a plain one is named by what it says if it says anything, and otherwise by where it came from: the record type's module if a record type was being read, or else the function that raised it. """ name = type(error).__name__ if type(error) is not dns.exception.FormError: return name # One raised with nothing to say is given the class's own default text. said = str(error) if said != str(dns.exception.FormError()): return "%s: %s" % (name, said.splitlines()[0]) frames = [ frame for frame in traceback.extract_tb(error.__traceback__) if "/dns/" in frame.filename ] rdtypes = [frame for frame in frames if "/dns/rdtypes/" in frame.filename] if rdtypes: return "%s in %s" % (name, _module(rdtypes[-1])) # The byte reader and the exception wrapper are where everything goes # wrong and say nothing about why. callers = [ frame for frame in frames if not frame.filename.endswith( ("/dns/wire.py", "/dns/wirebase.py", "/dns/exception.py") ) ] if callers: return "%s in %s.%s" % (name, _module(callers[-1]), callers[-1].name) return name
def _module(frame): return os.path.splitext(os.path.basename(frame.filename))[0]
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 most of the classes in EXPECTED turn up in it. The rest are # rarer than that, and some 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", ) options = parser.parse_args()
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, 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[len("ERR ") :])].append(raw) elif they_accept: classes[("mine", ours.split()[1])].append(raw) else: both_err += 1
print( "%d messages from seed %d: both accept %d, both refuse %d, disagree %d" % ( options.count, options.seed, 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( " %-6s %-40s %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())