cd-check.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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: name(root) + type(41) + class(extflags=DO)
  16. # + ttl(udp-size) + rdlength(0). The 32-bit TTL field must be present.
  17. opt = b"\x00" + struct.pack(">HHIH", 41, 0x8000, 0, 0)
  18. hdr = struct.pack(">HHHHHH", tid, flags, 1, 0, 0, 1)
  19. pkt = hdr + name + struct.pack(">HH", qtype, qclass) + opt
  20. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  21. s.settimeout(5)
  22. try:
  23. s.sendto(pkt, (ip, port))
  24. data, _ = s.recvfrom(4096)
  25. rcode = data[3] & 0x0F
  26. print(f"CD+DO query rcode={rcode} (0=NOERROR, 2=SERVFAIL)")
  27. if rcode == 0:
  28. sys.exit(0)
  29. if rcode == 2:
  30. sys.exit(1)
  31. sys.exit(2)
  32. except Exception as e:
  33. print(f"CD probe error: {e}")
  34. sys.exit(2)
  35. finally:
  36. s.close()