broken-zone-responder.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env python3
  2. """Static DNS responder for the controlled broken.example zone.
  3. Serves two pre-built response packets, selected by the query name:
  4. - www.broken.example -> the A-answer packet (valid OR broken, given by argv[1])
  5. - broken.example -> the DNSKEY packet (argv[2]); needed so unbound can
  6. prime the trust anchor (it fetches the zone DNSKEY)
  7. The transaction ID of the served packet is patched to match the query, so the
  8. responses are matched to the right request.
  9. Usage: python broken-zone-responder.py <a-packet.bin> <dnskey-packet.bin> <port>
  10. """
  11. import socket
  12. import sys
  13. import time
  14. def parse_qname(data):
  15. """Extract the question name from a DNS query (data is the full packet)."""
  16. i = 12 # after the 12-byte header
  17. labels = []
  18. while i < len(data):
  19. ln = data[i]
  20. if ln == 0:
  21. i += 1
  22. break
  23. i += 1
  24. labels.append(data[i:i + ln].decode("ascii", "replace"))
  25. i += ln
  26. return ".".join(labels) + "."
  27. apkt = open(sys.argv[1], "rb").read()
  28. dnskey_pkt = open(sys.argv[2], "rb").read()
  29. port = int(sys.argv[3])
  30. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  31. s.bind(("0.0.0.0", port))
  32. # Determine this container's own IP (connect to a public address; no packet
  33. # is sent — UDP connect just selects the local address). This is more
  34. # reliable than `docker inspect` from the host, which can be empty while the
  35. # container is starting on a slow WSL daemon.
  36. try:
  37. probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  38. probe.connect(("1.1.1.1", 53))
  39. my_ip = probe.getsockname()[0]
  40. probe.close()
  41. except Exception:
  42. my_ip = "0.0.0.0"
  43. print(f"responder ip={my_ip} on :{port} "
  44. f"(a={len(apkt)}B dnskey={len(dnskey_pkt)}B)", flush=True)
  45. n = 0
  46. while True:
  47. data, addr = s.recvfrom(4096)
  48. n += 1
  49. if len(data) < 12:
  50. continue
  51. qname = parse_qname(data)
  52. if qname.startswith("www.broken.example"):
  53. pkt = apkt
  54. elif qname.startswith("broken.example"):
  55. pkt = dnskey_pkt
  56. else:
  57. pkt = apkt
  58. print(f"[{time.time():.0f}] query #{n} from {addr[0]} q={qname}", flush=True)
  59. # patch the transaction ID to match the query
  60. resp = data[:2] + pkt[2:]
  61. s.sendto(resp, addr)