dns-check.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # DNSSEC verification probe for unbound-sec.
  2. #
  3. # Builds a correct EDNS0 query. The DO (DNSSEC OK) bit lives in the OPT
  4. # record's 4-byte TTL/EXTFLAGS field (0x8000); the header must carry
  5. # arcount=1 when the OPT record is present. We then assert on the AD
  6. # (authenticated data) bit in the response header.
  7. #
  8. # Checks (all deterministic, no dependency on third-party zone signing):
  9. # 1. signed zone + DO -> NOERROR, answers, AD=1 (validation works)
  10. # 2. signed zone, no DO -> NOERROR, answers, AD=0 (AD only when requested)
  11. # 3. signed zone + DO -> NOERROR, answers, AD=1 (repeat, stability)
  12. #
  13. # A separate restart-persistence check lives in run-tests.sh.
  14. import socket
  15. import struct
  16. import sys
  17. server = sys.argv[1] if len(sys.argv) > 1 else "unbound"
  18. port = int(sys.argv[2]) if len(sys.argv) > 2 else 5053
  19. def enc(name):
  20. out = b""
  21. for p in name.rstrip(".").split("."):
  22. out += bytes([len(p)]) + p.encode()
  23. return out + b"\x00"
  24. def query(name, qtype, do_bit, tries=5):
  25. import time
  26. tid = 0x1234
  27. flags = 0x0100 # RD
  28. arcount = 1 if do_bit else 0
  29. header = struct.pack(">HHHHHH", tid, flags, 1, 0, 0, arcount)
  30. q = header + enc(name) + struct.pack(">HH", qtype, 1) # type, IN
  31. if do_bit:
  32. # OPT: root name, type=41, class=0, TTL/EXTFLAGS=DO(0x8000), rdlen=0
  33. q += b"\x00" + struct.pack(">HHIH", 41, 0, 0x8000, 0)
  34. last = None
  35. for attempt in range(tries):
  36. if attempt:
  37. time.sleep(2) # backoff between retries (WSL net hiccups)
  38. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  39. s.settimeout(15)
  40. try:
  41. s.sendto(q, (server, port))
  42. data, _ = s.recvfrom(4096)
  43. except socket.timeout as e:
  44. last = e
  45. continue
  46. finally:
  47. s.close()
  48. rf = struct.unpack(">H", data[2:4])[0]
  49. an = struct.unpack(">H", data[6:8])[0]
  50. ad = (rf >> 5) & 1
  51. rc = rf & 0xF
  52. return an, ad, rc
  53. raise last
  54. def check(label, name, qtype, do_bit, want_ad, want_rc=0):
  55. an, ad, rc = query(name, qtype, do_bit)
  56. good = (rc == want_rc) and (an > 0) and (ad == want_ad)
  57. print(f"{label}: answers={an} AD={ad} rcode={rc} -> {'PASS' if good else 'FAIL'}")
  58. return good
  59. ok = True
  60. # 1) signed zone, DO -> AD=1
  61. ok &= check("signed example.com A (DO) ", "example.com", 1, True, want_ad=1)
  62. # 2) signed zone, no DO -> AD=0
  63. ok &= check("signed example.com A (no DO)", "example.com", 1, False, want_ad=0)
  64. # 3) repeat signed+DO for stability -> AD=1
  65. ok &= check("signed example.com A (DO) ", "example.com", 1, True, want_ad=1)
  66. sys.exit(0 if ok else 1)