Python dns.resolver.NXDOMAIN Examples

The following are 30 code examples of dns.resolver.NXDOMAIN(). 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: 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 #2
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 #3
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 #4
Source File: dns_handler.py    From Raccoon with MIT License 6 votes vote down vote up
def query_dns(cls, domains, records):
        """
        Query DNS records for host.
        :param domains: Iterable of domains to get DNS Records for
        :param records: Iterable of DNS records to get from domain.
        """
        results = {k: set() for k in records}
        for record in records:
            for domain in domains:
                try:
                    answers = cls.resolver.query(domain, record)
                    for answer in answers:
                        # Add value to record type
                        results.get(record).add(answer)
                except (resolver.NoAnswer, resolver.NXDOMAIN, resolver.NoNameservers):
                    # Type of record doesn't fit domain or no answer from ns
                    continue

        return {k: v for k, v in results.items() if v} 
Example #5
Source File: url.py    From sync-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_mx_domains(domain, dns_resolver=_dns_resolver):
    """ Retrieve and return the MX records for a domain. """
    mx_records = []
    try:
        mx_records = dns_resolver().query(domain, 'MX')
    except NoNameservers:
        log.error('NoMXservers', domain=domain)
    except NXDOMAIN:
        log.error('No such domain', domain=domain)
    except Timeout:
        log.error('Time out during resolution', domain=domain)
        raise
    except NoAnswer:
        log.error('No answer from provider', domain=domain)
        mx_records = _fallback_get_mx_domains(domain)

    return [str(rdata.exchange).lower() for rdata in mx_records] 
Example #6
Source File: __init__.py    From bearded-avenger with Mozilla Public License 2.0 6 votes vote down vote up
def resolve_ns(data, t='A', timeout=HUNTER_RESOLVER_TIMEOUT):
    resolver = dns.resolver.Resolver()
    resolver.timeout = timeout
    resolver.lifetime = timeout
    resolver.search = []
    try:
        answers = resolver.query(data, t)
        resp = []
        for rdata in answers:
            resp.append(rdata)
    except (NoAnswer, NXDOMAIN, EmptyLabel, NoNameservers, Timeout) as e:
        if str(e).startswith('The DNS operation timed out after'):
            logger.info('{} - {} -- this may be normal'.format(data, e))
            return []

        if not str(e).startswith('The DNS response does not contain an answer to the question'):
            if not str(e).startswith('None of DNS query names exist'):
                logger.info('{} - {}'.format(data, e))
        return []

    return resp 
Example #7
Source File: test_rbl.py    From pygameweb with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_rbl():
    """ handles failure ok, and handles lookups ok with dns module.
    """
    import mock
    from dns.resolver import NoAnswer, NXDOMAIN, NoNameservers

    from pygameweb.user.rbl import rbl

    assert rbl('127.0.0.1') is False
    assert rbl('') is False

    with mock.patch('dns.resolver.query') as query:
        query.side_effect = NoAnswer()
        assert rbl('192.168.0.1') is False
        query.side_effect = NXDOMAIN()
        assert rbl('192.168.0.1') is False
        query.side_effect = NoNameservers()
        assert rbl('192.168.0.1') is False

    with mock.patch('dns.resolver.query') as query:
        query.side_effect = '127.0.0.2'
        assert rbl('192.168.0.1') is True
        assert query.called 
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: 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 #10
Source File: __init__.py    From cloud-inquisitor with Apache License 2.0 6 votes vote down vote up
def dns_record_exists(record):
    """Try and resolve a DNS record to see if it exists

    Args:
        record (str): DNS records to attempt to resolve

    Returns:
        `bool`
    """
    try:
        query(record)
        return True
    except NXDOMAIN:
        return False
# endregion 
Example #11
Source File: hooks.py    From dnsrobocert with MIT License 6 votes vote down vote up
def _check_one_challenge(challenge: str, token: Optional[str]) -> bool:
    try:
        answers = resolver.query(challenge, "TXT")
    except (resolver.NXDOMAIN, resolver.NoAnswer):
        print("TXT {0} does not exist.".format(challenge))
        return False
    else:
        print("TXT {0} exists.".format(challenge))

    if token:
        validation_answers = [
            rdata
            for rdata in answers
            for txt_string in rdata.strings
            if txt_string.decode("utf-8") == token
        ]

        if not validation_answers:
            print("TXT {0} does not have the expected token value.".format(challenge))
            return False

        print("TXT {0} has the expected token value.")

    return True 
Example #12
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 #13
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 #14
Source File: test_lookup_dns.py    From PyFunceble with Apache License 2.0 5 votes vote down vote up
def test_record_NXDOMAIN(self):
        """
        Tests the method which let us get the AAAA record for the case that
        we get a NXDOMAIN exception.
        """

        self.dns_lookup.resolver.query = Mock(side_effect=NXDOMAIN())

        expected = None
        actual = self.dns_lookup.aaaa_record(self.subject)

        self.assertEqual(expected, actual) 
Example #15
Source File: endpoints.py    From OpenResolve with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get(self, rdtype, domain):
        t1 = time.time()

        rdtype = rdtype.upper()
        current_app.logger.info(
            'Request from %s - %s', request.remote_addr, rdtype)
        self.valid_args(rdtype, domain)

        # Iterate through nameservers so that we can tell which one gets used.
        nameservers = current_app.config['RESOLVERS']
        for nameserver in nameservers:
            dns_resolver.nameservers = [nameserver]
            try:
                answer = dns_resolver.query(
                    domain, rdtype, raise_on_no_answer=False)
                # Successful query
                break
            except (NoNameservers, NXDOMAIN):
                # TODO: this should still follow the RFC
                return {'message': "No nameservers found for provided domain"}, 404
            except Timeout as e:
                # Communication fail or timeout - try next nameserver
                if nameserver is nameservers[-1]:
                    current_app.logger.info(e)
                    return {'message': 'All nameservers timed out.'}, 503
                continue
            except Exception as e:
                current_app.logger.error(e)
                return {'message': 'An unexpected error occured.'}, 500

        t2 = time.time()
        duration = t2 - t1

        return parse_query(answer, nameserver, duration) 
Example #16
Source File: uri_parser.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _get_dns_txt_options(hostname):
    try:
        results = resolver.query(hostname, 'TXT')
    except (resolver.NoAnswer, resolver.NXDOMAIN):
        # No TXT records
        return None
    except Exception as exc:
        raise ConfigurationError(str(exc))
    if len(results) > 1:
        raise ConfigurationError('Only one TXT record is supported')
    return (
        b'&'.join([b''.join(res.strings) for res in results])).decode('utf-8') 
Example #17
Source File: endpoints.py    From OpenResolve with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get(self, ip):
        t1 = time.time()
        self.valid_args(ip)

        # Iterate through nameservers so that we can tell which one gets used.
        nameservers = current_app.config['RESOLVERS']
        for nameserver in nameservers:
            dns_resolver.nameservers = [nameserver]
            try:
                # http://stackoverflow.com/a/19867936/1707152
                answer = dns_resolver.query(
                    reversename.from_address(ip), rdatatype.PTR,
                    raise_on_no_answer=False)
                # Successful query
                break
            except Timeout as e:
                # Communication fail or timeout - try next nameserver
                if nameserver is nameservers[-1]:
                    current_app.logger.info(e)
                    return {'message': 'All nameservers timed out.'}, 503
                continue
            except NXDOMAIN:
                return {'message': 'No nameserver found for the provided IP'}, 404
            except Exception as e:
                current_app.logger.error(e)
                return {'message': 'An unexpected error occured.'}, 500

        t2 = time.time()
        duration = t2 - t1

        if answer is None:
            return {'message': 'An unexpected error occured.'}, 500
        return parse_query(answer, nameserver, duration) 
Example #18
Source File: test_lookup_dns.py    From PyFunceble with Apache License 2.0 5 votes vote down vote up
def test_record_NXDOMAIN(self):
        """
        Tests the method which let us get the PTR record for the case that
        we get a NXDOMAIN exception.
        """

        self.dns_lookup.resolver.query = Mock(side_effect=NXDOMAIN())

        expected = None
        actual = self.dns_lookup.ptr_record(self.subject)

        self.assertEqual(expected, actual) 
Example #19
Source File: test_lookup_dns.py    From PyFunceble with Apache License 2.0 5 votes vote down vote up
def test_record_NXDOMAIN(self):
        """
        Tests the method which let us get the NS record for the case that
        we get a NXDOMAIN exception.
        """

        self.dns_lookup.resolver.query = Mock(side_effect=NXDOMAIN())

        expected = None
        actual = self.dns_lookup.ns_record(self.subject)

        self.assertEqual(expected, actual) 
Example #20
Source File: test_lookup_dns.py    From PyFunceble with Apache License 2.0 5 votes vote down vote up
def test_record_NXDOMAIN(self):
        """
        Tests the method which let us get the MX record for the case that
        we get a NXDOMAIN exception.
        """

        self.dns_lookup.resolver.query = Mock(side_effect=NXDOMAIN())

        expected = None
        actual = self.dns_lookup.mx_record(self.subject)

        self.assertEqual(expected, actual) 
Example #21
Source File: test_lookup_dns.py    From PyFunceble with Apache License 2.0 5 votes vote down vote up
def test_record_NXDOMAIN(self):
        """
        Tests the method which let us get the CNAME record for the case that
        we get a NXDOMAIN exception.
        """

        self.dns_lookup.resolver.query = Mock(side_effect=NXDOMAIN())

        expected = None
        actual = self.dns_lookup.cname_record(self.subject)

        self.assertEqual(expected, actual) 
Example #22
Source File: test_lookup_dns.py    From PyFunceble with Apache License 2.0 5 votes vote down vote up
def test_record_NXDOMAIN(self):
        """
        Tests the method which let us get the A record for the case that
        we get a NXDOMAIN exception.
        """

        self.dns_lookup.resolver.query = Mock(side_effect=NXDOMAIN())

        expected = None
        actual = self.dns_lookup.a_record(self.subject)

        self.assertEqual(expected, actual) 
Example #23
Source File: brute.py    From OneForAll with GNU General Public License v3.0 5 votes vote down vote up
def do_query_a(domain, resolver):
    try:
        answer = resolver.query(domain, 'A')
    # If resolve random subdomain raise timeout error, try again
    except Timeout as e:
        logger.log('ALERT', f'DNS resolve timeout, retrying')
        logger.log('DEBUG', e.args)
        raise tenacity.TryAgain
    # If resolve random subdomain raise NXDOMAIN, YXDOMAIN, NoAnswer, NoNameservers error
    # It means that there is no A record of random subdomain and not use wildcard dns record
    except (NXDOMAIN, YXDOMAIN, NoAnswer, NoNameservers) as e:
        logger.log('DEBUG', e.args)
        logger.log('INFOR', f'{domain} seems not use wildcard dns record')
        return False
    except Exception as e:
        logger.log('ALERT', f'Detect {domain} wildcard dns record error')
        logger.log('FATAL', e.args)
        exit(1)
    else:
        if answer.rrset is None:
            logger.log('ALERT', f'DNS resolve dont have result, retrying')
            raise tenacity.TryAgain
        ttl = answer.ttl
        name = answer.name
        ips = {item.address for item in answer}
        logger.log('ALERT', f'{domain} use wildcard dns record')
        logger.log('ALERT', f'{domain} resolve to: {name} '
                            f'IP: {ips} TTL: {ttl}')
        return True 
Example #24
Source File: brute.py    From OneForAll with GNU General Public License v3.0 5 votes vote down vote up
def get_wildcard_record(domain, resolver):
    logger.log('INFOR', f'Query {domain} \'s wildcard dns record in authoritative name server')
    try:
        answer = resolver.query(domain, 'A')
    # 如果查询随机域名A记录时抛出Timeout异常则重新查询
    except Timeout as e:
        logger.log('ALERT', f'Query timeout, retrying')
        logger.log('DEBUG', e.args)
        raise tenacity.TryAgain
    except (NXDOMAIN, YXDOMAIN, NoAnswer, NoNameservers) as e:
        logger.log('DEBUG', e.args)
        logger.log('INFOR', f'{domain} dont have A record on authoritative name server')
        return None, None
    except Exception as e:
        logger.log('ERROR', e.args)
        logger.log('ERROR', f'Query {domain} wildcard dns record in authoritative name server error')
        exit(1)
    else:
        if answer.rrset is None:
            logger.log('DEBUG', f'No record of query result')
            return None, None
        name = answer.name
        ip = {item.address for item in answer}
        ttl = answer.ttl
        logger.log('INFOR', f'{domain} results on authoritative name server: {name} '
                            f'IP: {ip} TTL: {ttl}')
        return ip, ttl 
Example #25
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 #26
Source File: dnspython.py    From vpn-slice with GNU General Public License v3.0 5 votes vote down vote up
def lookup_host(self, hostname, keep_going=True):
        result = set()

        for source in self.bind_addresses or [None]:
            if source is None:
                self.resolver.nameservers = self.nameservers
            else:
                self.resolver.nameservers = [str(dns) for dns in self.dns_servers if dns.version == source.version]
                if not self.resolver.nameservers:
                    continue

            for rectype in self.rectypes:
                try:
                    # print("Issuing query for hostname %r, rectype %r, source %r, search_domains %r, nameservers %r" % (
                    #     hostname, rectype, source, self.resolver.search_domains, self.resolver.nameservers), file=stderr)
                    a = self.resolver.query(hostname, rectype, source=str(source))
                    print("Got results: %r" % list(a), file=stderr)
                except (NXDOMAIN, NoAnswer):
                    pass
                except Timeout:
                    # No point in retrying with a different rectype if these DNS server(s) are not responding
                    break
                else:
                    result.update(ip_address(r.address) for r in a)
                if result and not keep_going:
                    return result

        return result or None 
Example #27
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 #28
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 #29
Source File: srv_resolver.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def get_options(self):
        try:
            results = resolver.query(self.__fqdn, 'TXT',
                                     lifetime=self.__connect_timeout)
        except (resolver.NoAnswer, resolver.NXDOMAIN):
            # No TXT records
            return None
        except Exception as exc:
            raise ConfigurationError(str(exc))
        if len(results) > 1:
            raise ConfigurationError('Only one TXT record is supported')
        return (
            b'&'.join([b''.join(res.strings) for res in results])).decode(
            'utf-8') 
Example #30
Source File: resolve_hostnames.py    From yeti with Apache License 2.0 4 votes vote down vote up
def consumer(self):
        while True:
            try:
                hostname, rtype = self.queue.get(True, 5)
            except Empty:
                logging.debug("Empty! Bailing")
                return
            try:
                logging.debug("Starting work on {}".format(hostname))
                results = self.resolver.query(hostname, rtype)
                if results:
                    if hostname not in self.results:
                        self.results[hostname] = {}
                    text_results = []
                    for r in results:
                        if isinstance(r, NS_class):
                            text_results.append(r.target.to_text())
                        elif isinstance(r, A_class):
                            text_results.append(r.to_text())
                        else:
                            logging.error(
                                "Unknown record type: {}".format(type(r)))
                    hostname = Hostname(value=hostname)
                    ResolveHostnames.each(hostname, rtype, text_results)
            except NoAnswer:
                continue
            except NXDOMAIN:
                continue
            except Timeout:
                logging.debug("Request timed out for {}".format(hostname))
                continue
            except NoNameservers:
                continue
            except Exception as e:
                import traceback
                logging.error(
                    "Unknown error occurred while working on {} ({})".format(
                        hostname, rtype))
                logging.error("\nERROR: {}".format(hostname, rtype, e))
                logging.error(traceback.print_exc())

            continue