Python dns.resolver.Resolver() Examples

The following are 27 code examples of dns.resolver.Resolver(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module dns.resolver , or try the search function .
Example #1
Source File: ccp_util.py    From ciscoconfparse with GNU General Public License v3.0 8 votes vote down vote up
def dns6_lookup(input, timeout=3, server=""):
    """Perform a simple DNS lookup, return results in a dictionary"""
    resolver = Resolver()
    resolver.timeout = float(timeout)
    resolver.lifetime = float(timeout)
    if server:
        resolver.nameservers = [server]
    try:
        records = resolver.query(input, "AAAA")
        return {
            "addrs": [ii.address for ii in records],
            "error": "",
            "name": input,
        }
    except DNSException as e:
        return {
            "addrs": [],
            "error": repr(e),
            "name": input,
        } 
Example #2
Source File: ccp_util.py    From ciscoconfparse with GNU General Public License v3.0 8 votes vote down vote up
def dns_lookup(input, timeout=3, server=""):
    """Perform a simple DNS lookup, return results in a dictionary"""
    resolver = Resolver()
    resolver.timeout = float(timeout)
    resolver.lifetime = float(timeout)
    if server:
        resolver.nameservers = [server]
    try:
        records = resolver.query(input, "A")
        return {
            "addrs": [ii.address for ii in records],
            "error": "",
            "name": input,
        }
    except DNSException as e:
        return {
            "addrs": [],
            "error": repr(e),
            "name": input,
        } 
Example #3
Source File: cloudfront.py    From Sitadel with GNU General Public License v3.0 7 votes vote down vote up
def process(self, headers, content):
        request = Services.get("request_factory")
        hostname = urlparse(request.url).hostname
        _ = False
        try:
            resolver = Resolver(configure=False)
            resolver.nameservers = [settings.dns_resolver]
            resolver.timeout = 2
            resolver.lifetime = 2

            dns_query = resolver.query(hostname, "CNAME")

            if len(dns_query) > 0:
                for answer in dns_query:
                    _ |= re.search(r"cloudfront\.net", str(answer), re.I) is not None
            if _:
                return "CloudFront CDN (Amazon)"
        except NoAnswer:
            pass
        except NXDOMAIN:
            pass
        except Timeout:
            pass 
Example #4
Source File: checkresolvers.py    From dnsbrute with MIT License 7 votes vote down vote up
def check_for_wildcards(args, server, name, rectype, tries=4):
    """
    Verify that the DNS server doesn't return wildcard results for domains
    which don't exist, it should correctly return NXDOMAIN.
    """
    resolver = Resolver()
    resolver.timeout = args.timeout
    resolver.lifetime = args.timeout
    resolver.nameservers = [server]
    nx_names = [base64.b32encode(
                    os.urandom(
                        random.randint(8, 10))
                ).strip('=').lower() + name
                for _ in range(0, tries)]
    correct_result_count = 0
    for check_nx_name in nx_names:
        try:
            result = resolver.query(check_nx_name, rectype)            
            return False  # Any valid response = immediate fail!
        except (NXDOMAIN, NoNameservers):
            correct_result_count += 1
        except DNSException:
            continue        
    return correct_result_count > (tries / 2.0) 
Example #5
Source File: urlextract_core.py    From URLExtract with MIT License 6 votes vote down vote up
def dns_cache_install():
    try:
        from dns_cache.resolver import ExceptionCachingResolver
        from dns import resolver as dnspython_resolver_module
        if not dnspython_resolver_module.default_resolver:
            dnspython_resolver_module.default_resolver = ExceptionCachingResolver()
        del dnspython_resolver_module
    except ImportError:
        pass

    try:
        from dns.resolver import LRUCache, Resolver, override_system_resolver, _resolver, default_resolver
    except ImportError:
        return

    if default_resolver:
        if not default_resolver.cache:
            default_resolver.cache = LRUCache()
        resolver = default_resolver
    elif _resolver and _resolver.cache:
        resolver = _resolver
    else:
        resolver = Resolver()
        resolver.cache = LRUCache()
    override_system_resolver(resolver) 
Example #6
Source File: checkresolvers.py    From dnsbrute with MIT License 6 votes vote down vote up
def time_resolve(args, server, name, rectype, tries=3):
    """
    Time how long it takes to resolve a name using the server
    """
    resolver = Resolver()
    resolver.timeout = args.timeout
    resolver.lifetime = args.timeout
    resolver.nameservers = [server]
    results = []

    while tries > 0:
        start = time.time()
        try:
            result = resolver.query(name, rectype)
        except DNSException as ex:
            end = time.time()
            LOG.debug("%s failed in %.2fs", server, end - start)
            result = ex
        else:
            end = time.time()
            LOG.debug("%s resolved %s %s in %.2fs", server, name, rectype, end - start)
        results.append((end - start, result))
        tries -= 1
    return server, check_results(results), results 
Example #7
Source File: tasks.py    From DevOps with GNU General Public License v2.0 6 votes vote down vote up
def reflush(obj, nameserver):
    r = resolver.Resolver()
    r.nameservers = [nameserver]
    try:
        answers = r.query(obj.url, 'CNAME')
        for rdata in answers:
            return rdata.to_text()[:-1]
    except resolver.NoAnswer as e:
        try:
            answer = r.query(obj.url, 'A')
            for rr in answer:
                return rr.address
        except Exception as e:
            pass
    except resolver.NXDOMAIN as e:
        return ''
    return '' 
Example #8
Source File: fastly.py    From Sitadel with GNU General Public License v3.0 6 votes vote down vote up
def process(self, headers, content):
        request = Services.get("request_factory")
        hostname = urlparse(request.url).hostname
        _ = False
        try:
            resolver = Resolver(configure=False)
            resolver.nameservers = [settings.dns_resolver]
            resolver.timeout = 2
            resolver.lifetime = 2

            dns_query = resolver.query(hostname, "CNAME")
            if len(dns_query) > 0:
                for answer in dns_query:
                    _ |= re.search(r"fastly\.net", str(answer), re.I) is not None
            if _:
                return "Fastly CDN"
        except NoAnswer:
            pass
        except NXDOMAIN:
            pass
        except Timeout:
            pass 
Example #9
Source File: cloudflare.py    From Sitadel with GNU General Public License v3.0 6 votes vote down vote up
def process(self, headers, content):
        request = Services.get("request_factory")
        hostname = urlparse(request.url).hostname
        try:
            resolver = Resolver(configure=False)
            resolver.nameservers = [settings.dns_resolver]
            resolver.timeout = 2
            resolver.lifetime = 2
            dns_query = resolver.query(hostname + ".cdn.cloudflare.net", "A")

            if len(dns_query) > 0:
                return "Cloudflare CDN"

        except NXDOMAIN:
            pass
        except NoAnswer:
            pass
        except Timeout:
            pass 
Example #10
Source File: azure.py    From Sitadel with GNU General Public License v3.0 6 votes vote down vote up
def process(self, headers, content):
        request = Services.get("request_factory")
        hostname = urlparse(request.url).hostname
        _ = False

        try:
            resolver = Resolver(configure=False)
            resolver.nameservers = [settings.dns_resolver]
            resolver.timeout = 2
            resolver.lifetime = 2

            dns_query = resolver.query(hostname, "CNAME")
            if len(dns_query) > 0:
                for answer in dns_query:
                    _ |= re.search(r"azureedge\.net", str(answer), re.I) is not None
            if _:
                return "Azure CDN"
        except NoAnswer:
            pass
        except NXDOMAIN:
            pass
        except Timeout:
            pass 
Example #11
Source File: akamai.py    From Sitadel with GNU General Public License v3.0 6 votes vote down vote up
def process(self, headers, content):
        request = Services.get("request_factory")
        hostname = urlparse(request.url).hostname
        try:
            resolver = Resolver(configure=False)
            resolver.nameservers = [settings.dns_resolver]
            resolver.timeout = 2
            resolver.lifetime = 2

            dns_query = resolver.query(hostname + ".edgekey.net", "A")

            if len(dns_query) > 0:
                return "Akamai CDN"

        except NXDOMAIN:
            pass
        except NoAnswer:
            pass
        except Timeout:
            pass 
Example #12
Source File: acmedns.py    From sewer with MIT License 5 votes vote down vote up
def create_dns_record(self, domain_name, domain_dns_value):
        self.logger.info("create_dns_record")

        resolver = Resolver(configure=False)
        resolver.nameservers = ["8.8.8.8"]
        answer = resolver.query("_acme-challenge.{0}.".format(domain_name), "TXT")
        subdomain, _ = str(answer.canonical_name).split(".", 1)

        url = urllib.parse.urljoin(self.ACME_DNS_API_BASE_URL, "update")
        headers = {"X-Api-User": self.ACME_DNS_API_USER, "X-Api-Key": self.ACME_DNS_API_KEY}
        body = {"subdomain": subdomain, "txt": domain_dns_value}
        update_acmedns_dns_record_response = requests.post(
            url, headers=headers, json=body, timeout=self.HTTP_TIMEOUT
        )
        self.logger.debug(
            "update_acmedns_dns_record_response. status_code={0}. response={1}".format(
                update_acmedns_dns_record_response.status_code,
                log_response(update_acmedns_dns_record_response),
            )
        )
        if update_acmedns_dns_record_response.status_code != 200:
            # raise error so that we do not continue to make calls to ACME
            # server
            raise ValueError(
                "Error creating acme-dns dns record: status_code={status_code} response={response}".format(
                    status_code=update_acmedns_dns_record_response.status_code,
                    response=log_response(update_acmedns_dns_record_response),
                )
            )
        self.logger.info("create_dns_record_end") 
Example #13
Source File: __init__.py    From ActiveReign with GNU General Public License v3.0 5 votes vote down vote up
def resolve_host(host, dns_server):
    # Reuses ldap_srv value to resolve dns names (Assumes this is a DC)
    try:
        res = Resolver()
        res.timeout = 3
        res.lifetime = 3
        res.nameservers = [dns_server]
        dns_query = res.query(host, "A")
        for ip in dns_query:
            return ip
    except KeyboardInterrupt:
        exit(0)
    except:
        pass
    return '' 
Example #14
Source File: pfsense.py    From ansible-pfsense with GNU General Public License v3.0 5 votes vote down vote up
def resolve_hostname(address, dns_servers=None):
    """ get ip for hostname """
    if dns_servers is None:
        try:
            resolved_ip = socket.gethostbyname(address)
            return resolved_ip
        except socket.gaierror:
            pass
        msg = "Unable to resolve: {0}".format(address)
    else:
        error = None
        try:
            res = resolver.Resolver()
            res.timeout = 15
            res.lifetime = 15
            res.nameservers = dns_servers
            answers = res.query(address)
            if answers:
                return answers[0].address
        except exception.Timeout:
            error = 'timeout'

        msg = "Unable to resolve: {0} using {1} dns servers".format(address, ','.join(dns_servers))
        if error is not None:
            msg += ' ({0})'.format(error)

    raise AssertionError(msg) 
Example #15
Source File: ccp_util.py    From ciscoconfparse with GNU General Public License v3.0 5 votes vote down vote up
def reverse_dns_lookup(input, timeout=3, server=""):
    """Perform a simple reverse DNS lookup, return results in a dictionary"""
    assert _REVERSE_DNS_REGEX.search(input), "Invalid address format: '{0}'".format(
        input
    )
    resolver = Resolver()
    resolver.timeout = float(timeout)
    resolver.lifetime = float(timeout)
    if server:
        resolver.nameservers = [server]
    try:
        tmp = input.strip().split(".")
        tmp.reverse()
        inaddr = ".".join(tmp) + ".in-addr.arpa"
        records = resolver.query(inaddr, "PTR")
        return {
            "name": records[0].to_text(),
            "lookup": inaddr,
            "error": "",
            "addr": input,
        }
    except DNSException as e:
        return {
            "addrs": [],
            "lookup": inaddr,
            "error": repr(e),
            "name": input,
        } 
Example #16
Source File: url.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def _fallback_get_mx_domains(domain):
    """
    Sometimes dns.resolver.Resolver fails to return what we want. See
    http://stackoverflow.com/questions/18898847. In such cases, try using
    dns.query.udp().

    """
    try:
        query = dns.message.make_query(domain, dns.rdatatype.MX)
        answers = dns.query.udp(query, GOOGLE_DNS_IP).answer[0]
        return [a for a in answers if a.rdtype == dns.rdatatype.MX]
    except:
        return [] 
Example #17
Source File: dns_extension.py    From dynatrace-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_dns(dns_server: str, host: str) -> (bool, int):
    res = resolver.Resolver(configure=False)
    res.nameservers = [dns_server]
    res.lifetime = res.timeout = 2

    start = datetime.now()
    try:
        res.query(host, "A")
    except Exception as e:
        log.error(f"Failed executing the DNS test: {e}")
        return False, int((datetime.now() - start).total_seconds() * 1000)

    return True, int((datetime.now() - start).total_seconds() * 1000) 
Example #18
Source File: dkimsc4n.py    From dkimsc4n with MIT License 5 votes vote down vote up
def check_dkim_record(selector, domain):
    res = resolver.Resolver()
    nameservers = ["8.8.8.8", "1.1.1.1", "8.8.4.4", "1.0.0.1"]
    shuffle(nameservers)
    res.nameservers = nameservers

    try:
        answers = res.query(selector+"._domainkey."+domain, "TXT")
    except (resolver.NoAnswer, resolver.NXDOMAIN):
        answers = []
    if len(answers) > 1:
        # print (colored("\n[*] Error: selector: "+selector+" for domain: "+domain+" is misconfigured (received more than one DKIM back)", "magenta"))
        return (0, 0, 0, 0)
    elif not answers:
        pass
        return (0, 0, 0, 0)
    else:
        for rdata in answers:
            txt_string = str(b"".join(rdata.strings))
            dkim_type_p = re.findall(r'p=(.*?)(;|\s|$)',txt_string)
            if not(dkim_type_p):
                return (0, 0, 0, 0) # Can't apply my shitty regex
            else:
                asn_bytes = b64decode(str(dkim_type_p[0]))
                key_pub = RSA.importKey(asn_bytes)
                key_size = key_pub.size() + 1
        return (1, selector, domain, key_size) 
Example #19
Source File: connection.py    From plugin.video.ustvvod with GNU General Public License v2.0 5 votes vote down vote up
def connect(self):
		resolver = Resolver()
		resolver.nameservers = self._dnsproxy
		answer = resolver.query(self.host, 'A')
		self.host = answer.rrset.items[0].address
		self.sock = socket.create_connection((self.host, self.port)) 
Example #20
Source File: crimeflare.py    From cyber-security-framework with MIT License 5 votes vote down vote up
def __init__(self):
        super().__init__()
        self.resolver = Resolver()
        self.session = Session("http://www.crimeflare.com/cgi-bin/")
        actions = self.parser.add_mutually_exclusive_group(required = True)
        actions.add_argument("-s", "-cfs", "--search", metavar="DOMAIN", type=str, help="CloudFlare-Protected-Domain Search ...")
        actions.add_argument("-l", "-cfl", "--list", metavar="CFL-ID", type=str, help="List CloudFlare domains using the specified Direct-Connect IP Address ...")
        self.parser.add_argument("-x", "--proxy", default="", type=str, help="Proxify session through this proxy ('proto://a.ddr.es.s:port/') ...") 
Example #21
Source File: tasks.py    From DevOps with GNU General Public License v2.0 5 votes vote down vote up
def reflush(url, nameserver):
    r = resolver.Resolver()
    r.nameservers = [nameserver]
    try:
        answers = r.query(url, 'CNAME')
        for rdata in answers:
            return rdata.to_text()[:-1]
    except resolver.NoAnswer as e:
        return ''
    except resolver.NXDOMAIN as e:
        return ''
    return '' 
Example #22
Source File: tasks.py    From DevOps with GNU General Public License v2.0 5 votes vote down vote up
def reflush(url, nameserver):
    r = resolver.Resolver()
    r.nameservers = [nameserver]
    try:
        answers = r.query(url, 'CNAME')
        for rdata in answers:
            return rdata.to_text()[:-1]
    except resolver.NoAnswer as e:
        return ''
    except resolver.NXDOMAIN as e:
        return ''
    return '' 
Example #23
Source File: utils.py    From OneForAll with GNU General Public License v3.0 5 votes vote down vote up
def dns_resolver():
    """
    dns解析器
    """
    resolver = Resolver()
    resolver.nameservers = setting.resolver_nameservers
    resolver.timeout = setting.resolver_timeout
    resolver.lifetime = setting.resolver_lifetime
    return resolver 
Example #24
Source File: dnspython.py    From vpn-slice with GNU General Public License v3.0 5 votes vote down vote up
def configure(self, dns_servers, *, bind_addresses=None, search_domains=()):
        super().configure(dns_servers, bind_addresses=bind_addresses, search_domains=search_domains)

        self.resolver = Resolver(configure=False)
        self.resolver.domain = root
        self.resolver.search = [from_text(d) for d in search_domains]

        self.rectypes = []
        if self.bind_addresses is None or any(a.version == 4 for a in self.bind_addresses):
            self.rectypes.append('A')
        if self.bind_addresses is None or any(a.version == 6 for a in self.bind_addresses):
            self.rectypes.append('AAAA') 
Example #25
Source File: proxy.py    From plugin.video.ustvvod with GNU General Public License v2.0 5 votes vote down vote up
def connect(self):
		resolver = Resolver()
		resolver.nameservers = self._dnsproxy
		answer = resolver.query(self.host, 'A')
		self.host = answer.rrset.items[0].address
		self.sock = socket.create_connection((self.host, self.port)) 
Example #26
Source File: cloudflare_resolver.py    From arissploit with GNU General Public License v3.0 4 votes vote down vote up
def run():
	apianswer = {}

	ipresolver = resolver.Resolver()
	ipresolver.timeout = float(variables['timeout'][0])
	ipresolver.lifetime = float(variables['timeout'][0])

	variables['target'][0] = variables['target'][0].replace("http://", "")
	variables['target'][0] = variables['target'][0].replace("https://", "")
	sub = ('mail', 'webmail', 'email', 'direct-connect-mail',
	'direct', 'direct-connect', 'cpanel', 'phpmyadmin', 'ftp', 'forum', 'blog',
	'm', 'dev', 'record', 'ssl', 'dns', 'help', 'ns', 'ns1', 'ns2',
	'ns3', 'ns4', 'irc', 'server', 'status', 'portal', 'beta',
	'admin', 'alpha', 'imap', 'smtp', 'test')
	try:
		orgip = ipresolver.query(variables['target'][0], 'A')
		print(colors.green+"[-------------------------]"+colors.end)
		print(colors.green+"[+] Default IP Address: %s"%orgip[0]+colors.end)
		print(colors.green+"[-------------------------]"+colors.end)
		apianswer[variables['target'][0]] = orgip
	except(dns.exception.Timeout):
		print("\033[1;31m[-]\033[0m [-] Error: Host is down!"+colors.end)
	except dns.resolver.NoAnswer:
		print("\033[1;31m[-]\033[0m [?] The DNS response does not contain an answer to the question."+colors.end)
	for i in sub:
		host = i+'.'+variables['target'][0]
		try:
			query = ipresolver.query(host, 'A')
			if query[0] == orgip[0]:
				print(colors.yellow+"[?] %s: %s"%(host, query[0])+colors.end)
				apianswer[host] = query[0]
			else:
				print(colors.green+"[+] %s: %s"%(host, query[0])+colors.end)
				apianswer[host] = query[0]
		except(dns.exception.Timeout):
			if variables['pos'][0] != 'true':
				print("\033[1;31m[-]\033[0m [-] %s: N/A"%host+colors.end)
		except dns.resolver.NoAnswer:
			if variables['pos'][0] != 'true':
				print("\033[1;31m[-]\033[0m [?] The DNS response does not contain an answer to the question."+colors.end)

	return apianswer 
Example #27
Source File: domain.py    From BloodHound.py with MIT License 4 votes vote down vote up
def __init__(self, domain=None, auth=None, nameserver=None, dns_tcp=False):
        self.domain = domain
        # Object of type ADDomain, added later
        self.domain_object = None
        self.auth = auth
        # List of DCs for this domain. Contains just one DC since
        # we query for the primary DC specifically
        self._dcs = []
        # Kerberos servers
        self._kdcs = []
        # Global catalog servers
        self._gcs = []

        self.domains = {}
        self.nbdomains = {}
        self.groups = {} # Groups by DN
        self.groups_dnmap = {} # Group mapping from gid to DN
        self.computers = {}
        self.users = {} # Users by DN

        # Create a resolver object
        self.dnsresolver = resolver.Resolver()
        if nameserver:
            self.dnsresolver.nameservers = [nameserver]
        # Resolve DNS over TCP?
        self.dns_tcp = dns_tcp
        # Give it a cache to prevent duplicate lookups
        self.dnsresolver.cache = resolver.Cache()
        # Default timeout after 3 seconds if the DNS servers
        # do not come up with an answer
        self.dnsresolver.lifetime = 3.0
        # Also create a custom cache for both forward and backward lookups
        # this cache is thread-safe
        self.dnscache = DNSCache()
        # Create a thread-safe SID lookup cache
        self.sidcache = SidCache()
        # Create a thread-safe SAM lookup cache
        self.samcache = SamCache()
        # Create SID cache for computer accounts
        self.computersidcache = SidCache()
        # Object Resolver, initialized later
        self.objectresolver = None
        # Number of domains within the forest
        self.num_domains = 1
        # Does the schema have laps properties
        self.has_laps = False
        if domain is not None:
            self.baseDN = ADUtils.domain2ldap(domain)
        else:
            self.baseDN = None