I've been working on a script to detect whether a given hostname is part of a delegated zone. My goal is to use this for mapping out an organization's network by identifying domain delegations. The idea is to take a given hostname, run dig on it and see what kind of response it returns. I put together my own approach based on how I understand delegation works, but I'd love to get some expert eyes on it! Any feedback, improvements, or suggestions would be greatly appreciated. Here's the script: https://pastebin.com/CMKzACSm Thanks in advance! import subprocess import json import sys import logging # Configure logging for debugging def run_dig(hostname): try: # Run dig command for NS query result = subprocess.run(['dig', 'NS', hostname, '-4'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) return result.stdout except Exception as e: return str(e) def parse_dig_output(dig_output, hostname): response = { "details": { "delegated": False } } # Check if 'ANSWER SECTION' exists in the dig output if "ANSWER SECTION:" in dig_output: # Extract lines after 'ANSWER SECTION' and look for NS records answer_section = dig_output.split("ANSWER SECTION:")[1] ns_lines = [line.strip() for line in answer_section.splitlines() if "IN NS" in line] # Check if any NS lines contain the hostname at the start for line in ns_lines: ns_host = line.split()[0] if ns_host.startswith(hostname): response["details"]["delegated"] = True response["details"]["delegated_zone"] = hostname break # Check for rcode errors in the dig output error_codes = ['SERVFAIL', 'NXDOMAIN', 'REFUSED', 'NXRRSET', 'NOTAUTH', 'NOTZONE'] for error_code in error_codes: if f"rcode={error_code}" in dig_output: response["details"]["delegated"] = True break return response if response["details"]["delegated"] else None def main(): # Get the JSON input if len(sys.argv) < 2: sys.exit(1) input_data = json.loads(sys.argv[1]) hostname = input_data.get("value") if not hostname: sys.exit(1) # Run dig and parse the output dig_output = run_dig(hostname) result = parse_dig_output(dig_output, hostname) # Output only the entries with delegated: true if result: print(json.dumps([result], indent=2)) else: print("[]") if __name__ == "__main__": main()`` Continue reading...