#!/usr/bin/env python3 """Build a controlled DNSSEC zone (broken.example) as a binary DNS response packet. The zone presents a well-formed RRSIG (validly signed by its own DNSKEY) plus NSEC, but the DNSKEY cannot be anchored in the trust chain (broken.example is not delegated/signed by the root, and no parent DS exists). A validating resolver therefore MUST reject the data with SERVFAIL (without CD). Output: a DNS response packet for "www.broken.example A" suitable for a static UDP responder to serve to any query. """ import struct, sys from cryptography.hazmat.primitives.asymmetric import rsa import dns.dnssec, dns.zone, dns.name, dns.rdataclass, dns.rdatatype ORIGIN = "broken.example." z = dns.zone.from_text( """ broken.example. 300 IN SOA ns1.broken.example. admin.broken.example. 1 3600 900 604800 300 broken.example. 300 IN NS ns1.broken.example. ns1.broken.example. 300 IN A 192.0.2.53 www.broken.example. 300 IN A 192.0.2.1 """, origin=dns.name.from_text(ORIGIN), relativize=False, ) pk = rsa.generate_private_key(public_exponent=65537, key_size=2048) dnskey = dns.dnssec.make_dnskey(pk.public_key(), 8, flags=257, protocol=3) dns.dnssec.sign_zone(z, keys=[(pk, dnskey)], add_dnskey=True, deterministic=True, lifetime=3600) qname = dns.name.from_text("www.broken.example.") # Collect rrsets via iteration (find_rrset has a relativize quirk). # RRSIGs with different 'covers' are separate rdatasets -> gather all. a_rrset = None a_rrsig = None k_rrset = None for name, rds in z.iterate_rdatasets(): if name == qname and rds.rdtype == dns.rdatatype.A: a_rrset = rds if name == qname and rds.rdtype == dns.rdatatype.RRSIG: # pick the RRSIG that covers the A rrset if any(r.covers() == dns.rdatatype.A for r in rds): a_rrsig = rds if name == dns.name.from_text(ORIGIN) and rds.rdtype == dns.rdatatype.DNSKEY: k_rrset = rds ans = list(a_rrset) + list(a_rrsig) def enc(n): return n.to_wire() def rd_bytes(rd): w = rd.to_wire() return struct.pack(">HHIH", rd.rdtype, 1, 300, len(w)) + w tid = 0xabcd flags = 0x8500 # QR | AA | RA pkt = struct.pack(">HHHHHH", tid, flags, 1, len(ans), 0, len(k_rrset)) pkt += enc(qname) + struct.pack(">HH", 1, 1) for rd in ans: pkt += enc(qname) + rd_bytes(rd) for rd in k_rrset: pkt += enc(dns.name.from_text(ORIGIN)) + rd_bytes(rd) out = sys.argv[1] if len(sys.argv) > 1 else "broken-zone.bin" open(out, "wb").write(pkt) print(f"wrote {out}: {len(pkt)} bytes " f"({len(a_rrset)} A + {len(a_rrsig)} RRSIG answer, {len(k_rrset)} DNSKEY add'l)") print("A :", a_rrset[0].to_text()) print("RRSIG :", a_rrsig[0].to_text()[:75], "...") print("DNSKEY:", k_rrset[0].to_text()[:55], "...")