| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- #!/usr/bin/env python3
- """Static DNS responder for the controlled broken.example zone.
- Serves two pre-built response packets, selected by the query name:
- - www.broken.example -> the A-answer packet (valid OR broken, given by argv[1])
- - broken.example -> the DNSKEY packet (argv[2]); needed so unbound can
- prime the trust anchor (it fetches the zone DNSKEY)
- The transaction ID of the served packet is patched to match the query, so the
- responses are matched to the right request.
- Usage: python broken-zone-responder.py <a-packet.bin> <dnskey-packet.bin> <port>
- """
- import socket
- import sys
- import time
- def parse_qname(data):
- """Extract the question name from a DNS query (data is the full packet)."""
- i = 12 # after the 12-byte header
- labels = []
- while i < len(data):
- ln = data[i]
- if ln == 0:
- i += 1
- break
- i += 1
- labels.append(data[i:i + ln].decode("ascii", "replace"))
- i += ln
- return ".".join(labels) + "."
- apkt = open(sys.argv[1], "rb").read()
- dnskey_pkt = open(sys.argv[2], "rb").read()
- port = int(sys.argv[3])
- s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- s.bind(("0.0.0.0", port))
- # Determine this container's own IP (connect to a public address; no packet
- # is sent — UDP connect just selects the local address). This is more
- # reliable than `docker inspect` from the host, which can be empty while the
- # container is starting on a slow WSL daemon.
- try:
- probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- probe.connect(("1.1.1.1", 53))
- my_ip = probe.getsockname()[0]
- probe.close()
- except Exception:
- my_ip = "0.0.0.0"
- print(f"responder ip={my_ip} on :{port} "
- f"(a={len(apkt)}B dnskey={len(dnskey_pkt)}B)", flush=True)
- n = 0
- while True:
- data, addr = s.recvfrom(4096)
- n += 1
- if len(data) < 12:
- continue
- qname = parse_qname(data)
- if qname.startswith("www.broken.example"):
- pkt = apkt
- elif qname.startswith("broken.example"):
- pkt = dnskey_pkt
- else:
- pkt = apkt
- print(f"[{time.time():.0f}] query #{n} from {addr[0]} q={qname}", flush=True)
- # patch the transaction ID to match the query
- resp = data[:2] + pkt[2:]
- s.sendto(resp, addr)
|