cd-check.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/env python3
  2. """Send a DNS query with the DO and CD bits set; print the rcode.
  3. Usage: python cd-check.py <ip> <port>
  4. Exit: 0 if rcode==0 (NOERROR), 1 if rcode==2 (SERVFAIL), 2 otherwise/timeout.
  5. """
  6. import socket
  7. import struct
  8. import sys
  9. ip = sys.argv[1]
  10. port = int(sys.argv[2])
  11. name = b"\x03www\x08broken\x07example\x00" # www.broken.example
  12. qtype, qclass = 1, 1
  13. flags = 0x0110 # RD | CD
  14. tid = 0x1234
  15. # OPT record carrying the DO bit. The DO bit lives in the OPT record's 4-byte
  16. # EXTENDED FLAGS field (0x8000), NOT in the 2-byte CLASS field — this matches
  17. # how unbound (and dns-check.py) interpret it. Fields: type(41) + class(0) +
  18. # extflags(DO=0x8000) + rdlength(0).
  19. opt = b"\x00" + struct.pack(">HHIH", 41, 0, 0x8000, 0)
  20. hdr = struct.pack(">HHHHHH", tid, flags, 1, 0, 0, 1)
  21. pkt = hdr + name + struct.pack(">HH", qtype, qclass) + opt
  22. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  23. s.settimeout(5)
  24. try:
  25. s.sendto(pkt, (ip, port))
  26. data, _ = s.recvfrom(4096)
  27. rcode = data[3] & 0x0F
  28. print(f"CD+DO query rcode={rcode} (0=NOERROR, 2=SERVFAIL)")
  29. if rcode == 0:
  30. sys.exit(0)
  31. if rcode == 2:
  32. sys.exit(1)
  33. sys.exit(2)
  34. except Exception as e:
  35. print(f"CD probe error: {e}")
  36. sys.exit(2)
  37. finally:
  38. s.close()