#!/usr/bin/env python3 # -*- coding: utf-8 -*- # REQUIREMENTS: dnspython """ DNS Zone Transfer Test - Tests if zone transfers are possible for a given domain name. Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] """ # Imports from re import match #from os import geteuid from sys import exit from sys import argv from dns import resolver from dns.query import xfr from platform import system from dns.zone import from_xfr from dns.query import TransferError from dns.exception import FormError from argparse import ArgumentParser from subprocess import check_output from socket import gethostbyaddr, gethostbyname, herror __author__ = "Rodney O C Melby" __copyright__ = "Copyright 2022, Rodney O C Melby" __credits__ = ["Bob Halley"] __license__ = "LGPL v2.1" __version__ = "1.0.1" __maintainer__ = "Rodney O C Melby" __status__ = "Production" def colour_string(string, colour): """print coloured output on terminal for linux via ansi escape sequences or windows no color.""" coloured_string = "" if system() == "Linux": if colour == "GREEN": coloured_string = '\033[92m' + string + '\033[0m' print(coloured_string) if colour == "RED": coloured_string = '\033[91m' + string + '\033[0m' print(coloured_string) elif system() == "Windows": if colour == "GREEN": print(string) if colour == "RED": print(string) def get_local_name_server(): """ gets local dns for linux or windows, untested on mac os. """ if system() == "Windows": output = check_output(["ipconfig", "-all"]) ipconfig_all_list = output.decode('utf-8').split('\n') dns_ips = [] for i in range(0, len(ipconfig_all_list)): if "DNS Servers" in ipconfig_all_list[i]: # get the first dns server ip first_ip = ipconfig_all_list[i].split(":")[1].strip() print(first_ip) if not valid_ip(first_ip): # invalid ip print("Invalid Local DNS IP! change your DNS or use google with the flag -n 8.8.8.8.") exit(6) dns_ips.append(first_ip) # get all other dns server ips if they exist k = i+1 while k < len(ipconfig_all_list) and ":" not in ipconfig_all_list[k]: ip = ipconfig_all_list[k].strip() if valid_ip(ip): dns_ips.append(ip) k += 1 # at this point we're done break nameserver = dns_ips[0] return nameserver elif system() == "Linux" or system() == "Darwin": """ Returns the local machines nameserver IP or googles dns (LINUX/UNIX) """ nameserver = "1.1.1.1" with open("/etc/resolv.conf") as fh: for line in fh.readlines(): groups = match("nameserver (.*)", line) if groups: nameserver = groups.groups()[0] break return nameserver def ipv4(s): return str(int(s)) == s and 0 <= int(s) <= 255 def ipv6(s): if len(s) > 4: return False return int(s, 16) >= 0 and s[0] != '-' def valid_ip(address): """ Validates an IP address, return true or false. """ try: if address.count(".") == 3 and all(ipv4(i) for i in address.split(".")): return True if address.count(":") == 7 and all(ipv6(i) for i in address.split(":")): return True return False except ValueError: return False def get_target_nameservers(target, ns="1.1.1.1"): """ Returns a domain names name servers IP. """ server_ips, servers = [], [] if valid_ip(target): # handle IPs servers.append(target) else: # handle domain names my_resolver = resolver.Resolver() my_resolver.nameservers = [ns] try: nameservers = my_resolver.resolve(target, 'NS') # NS lookup for server in nameservers: # print(server) ip = gethostbyname(str(server)) # get NS ip server_ips.append(ip) servers.append(str(server)) except resolver.NoNameservers: colour_string("No DNS servers found at " + target, "RED") exit(-1) except resolver.NXDOMAIN: colour_string("The DNS query name does not exist: unknown domain " + target, "RED") exit(-1) except resolver.NoAnswer: colour_string("Cannot locate Nameservers from DNS lookup of A records at " + target + ", Try domain only not subdomains.", "RED") exit(-1) return server_ips, servers def get_target_subdomains_from_auth_ns(target, auth_ns): """ Checks domains nameserver for zone transfers, if allowed returns a list of enumerated subdomain DNS records""" if valid_ip(target): # handle IPs try: gethostbyaddr(str(target)) except herror: colour_string("Could not get hostname from " + str(target) + ", check target is live/up.", "RED") exit(-1) try: z = from_xfr(xfr(str(auth_ns), target)) # zone transfer dig request using authorized nameservers subdomains = [] names = z.nodes.keys() # node key values for n in names: at = match("@", str(n)) # removes dns self (@) symbol if not at: subdomain = str(n) + "." + target subdomains.append(subdomain) # print(subdomain) colour_string(target + " is VULNERABLE to DNS Zone Transfers!!!", "RED") return subdomains except TransferError: # most domains colour_string(target + " is SECURE against DNS Zone Transfers :-)", "GREEN") exit(1) except FormError: # google.co.uk colour_string(target + " is SECURE against DNS Zone Transfers :-)", "GREEN") exit(1) except TimeoutError: # rhul.ac.uk colour_string(target + " is VERY SECURE against DNS Zone Transfers :-)", "GREEN") exit(1) except OSError: # the next router colour_string("[No route to host] Lookup Failure!", "RED") colour_string("Domain name reverse fqdn lookup error - Check your on the domains internal network, or setup dnscrypt " + "for the domain as all european ISPs high-jack all dns traffic to censor the internet!", "RED") exit(1) def ztt(domain, nameserver=""): """ Zone Transfer Test for a Given Domain Name and/or nameserver """ # handle if user domain set if nameserver == "": nameserver = get_local_name_server() # get local nameservers target_nameservers, target_name = get_target_nameservers(domain, nameserver) # get target nameservers # For Users and Debugging print("Using DNS Server:\t", nameserver, " - ", gethostbyaddr(nameserver)[0]) print("Target Domain:\t\t", domain, " - ", gethostbyname(str(domain))) count = 0 for server in target_nameservers: host = target_name[count] count += 1 print("Target DNS " + str(count) + ": \t\t" + server + " - " + host) # test if nameserver lookup was ok try: subdomains = [] for server in target_nameservers: # attempt zone transfer to enumerate all subdomains subdomains = get_target_subdomains_from_auth_ns(domain, server) if len(subdomains) > 0: colour_string("Found " + str(len(subdomains)) + " subdomains at " + domain + " from nameserver " + server, "GREEN") for host in subdomains: print(host) # print(subdomains) if len(subdomains) > 0: exit(1) else: # no subdomains found colour_string("No subdomains found at " + domain, "RED") exit(1) except IndexError: colour_string("Domain Name Server lookup failed. Check domain name is correct and network connection is active!", "RED") exit(1) def ztt_file(filepath, nameserver=""): """ Reads a file of domains and uses ztt to check each domain and/or with optionally given nameserver """ # handle if nameserver set if nameserver == "": nameserver = get_local_name_server() # get local nameservers with open(filepath) as fh: for target in fh.read().splitlines(): ztt(target, nameserver) def parse_arguments(): """ parses command line arguments. """ # handle help and usage parser = ArgumentParser(description="Zone Transfer Tester: ztt tests IP's or domains for zone transfers. (XFR)") parser.add_argument('target', action="store", nargs="?", help="Target IP or Domain name to test") parser.add_argument('-f', "--file", action='store', dest="file", default=False, help='file of domain names to test, one per line') parser.add_argument('-n', "--nameserver", action='store', dest="nameserver", default=False, help='DNS IP for target DNS query, defaults to local DNS') arguments = parser.parse_args() return arguments #def require_root(): # """ method to require root privillages. """ # # handle optional positional arguments # if not geteuid() == 0: # check root permissions # print(RED + "Only root can run this script. Try using sudo!" + END) # exit(1) # if len(argv) > 5: # print("Too many arguments. One domain name only!") # exit(1) def check_user_input(arguments): """ checks user input for errors. """ # create illegal chars for DNS names and file names bad_dns_chars = [';', ':', '!', "*", '"', "'", '#', '$', '|', '%', '^', '&', '*', '(', ')', '<', '>', ',', '/', '?', '\\', '[', ']', '{', '}', '_', '+', '='] # illegal chars (special except dot and minus) bad__filename_chars = [';', ':', '!', "*", '"', "'", '#', '$', '|', '%', '^', '&', '*', '<', '>', '/', '?', '\\', '[', ']', '{', '}', '+', '='] # illegal chars (also no parentheses, commas, or underscores) # error if invalid user input if arguments.target: for character in arguments.target: if character in bad_dns_chars: print("Invalid target domain, or cannot locate DNS.") exit(3) if arguments.file: for character in arguments.file: if character in bad__filename_chars: print("Invalid filename - Valid Characters = a-z 0-9 .,()-_.") exit(4) if arguments.nameserver: for character in arguments.nameserver: if character in bad_dns_chars: print("Invalid nameserver given to perform lookup.") exit(5) def run_program(valid_arguments): """ runs the program dependant on arguments. """ # handle optional arguments if valid_arguments.target and valid_arguments.nameserver: ztt(valid_arguments.target, valid_arguments.nameserver) if valid_arguments.file and valid_arguments.nameserver: ztt_file(filename, valid_arguments.nameserver) if valid_arguments.target and not valid_arguments.nameserver: ztt(valid_arguments.target) if valid_arguments.file and not valid_arguments.nameserver: ztt_file(valid_arguments.file) if valid_arguments.nameserver and not valid_arguments.file and not valid_arguments.target: ztt("zonetransfer.me", valid_arguments.nameserver) if not valid_arguments.target and not valid_arguments.nameserver and not valid_arguments.file: ztt("zonetransfer.me") def main(): """ Main - parse arguments, checks user input, and performs a dns zone transfer against the target domain. """ # require_root() # require root or sudo args = parse_arguments() # parse user arguments check_user_input(args) # check for valid input else error run_program(args) # execute dns zone transfer on the target # TODO: maybe add ability to define custom dns server ip for zone transfer test (allows offline testing). if __name__ == '__main__': main()