Python dns.exception.DNSException() Examples

The following are 28 code examples of dns.exception.DNSException(). 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.exception , 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 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 #2
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 #3
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 #4
Source File: axfr.py    From octodns with MIT License 6 votes vote down vote up
def zone_records(self, zone):
        try:
            z = dns.zone.from_xfr(dns.query.xfr(self.master, zone.name,
                                                relativize=False),
                                  relativize=False)
        except DNSException:
            raise AxfrSourceZoneTransferFailed()

        records = []

        for (name, ttl, rdata) in z.iterate_rdatas():
            rdtype = dns.rdatatype.to_text(rdata.rdtype)
            records.append({
                "name": name.to_text(),
                "ttl": ttl,
                "type": rdtype,
                "value": rdata.to_text()
            })

        return records 
Example #5
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 #6
Source File: __init__.py    From dnsbrute with MIT License 6 votes vote down vote up
def _test_wildcard(self, domain, name):
        """
        Determine if a subdomain returns a wildcard entry
        """
        for query_type in ['A', 'AAAA', 'CNAME']:
            dnsname = name + '.' + domain
            try:
                resp = self.query(dnsname, query_type)
            except DNSException:
                # This is expected, but we ignore return type
                continue
            except Exception:
                LOG.exception("Whoopsie while testing wildcard")
                continue
            for query_type, result in self._format_results(query_type, resp):
                self._add_wildcard(domain, query_type, result)
        self.on_finish() 
Example #7
Source File: __init__.py    From dnsbrute with MIT License 6 votes vote down vote up
def run(self):
        lookups = self.rectypes or ['CNAME', 'A', 'AAAA']
        dnsname = self.domain
        if self.name is None:
            # Top-level, needs extra queries
            lookups += ['MX', 'SOA', 'NS', 'SRV', 'TXT', 'SPF', 'RRSIG', 'DS',
                        'DLV', 'DNSKEY']
        else:
            dnsname = '.'.join([self.name, dnsname])
        for query_type in set(lookups):
            resp = None
            LOG.debug("Checking %s %s", dnsname, query_type)
            try:
                resp = self.bruter.query(dnsname, query_type)
            except DNSException:
                continue
            except Exception:
                LOG.exception("While resolving %s %s", dnsname, query_type)
                continue
            self.bruter.on_result(self.domain, self.name, query_type, resp)
        self.bruter.on_finish() 
Example #8
Source File: etcd.py    From patroni with MIT License 5 votes vote down vote up
def get_srv_record(host):
        try:
            return [(r.target.to_text(True), r.port) for r in resolver.query(host, 'SRV')]
        except DNSException:
            return [] 
Example #9
Source File: dns.py    From PyFunceble with Apache License 2.0 5 votes vote down vote up
def ptr_record(self, subject, reverse_name=True, tcp=None):
        """
        Return the PTR record of the given subject (if found).

        :param str subject: The subject we are working with.
        :param bool tcp: Tell us to use TCP for query.

        :return: A list of PTR record(s).
        :rtype: list, None
        :raise ValueError: When a non string :code:`subject` is given.
        """

        if not subject or not isinstance(subject, str):
            raise ValueError(f"<subject> must be of type {str} and not empty.")

        if tcp is None:
            tcp = self.tcp

        PyFunceble.LOGGER.debug(f"Query over TCP: {self.tcp}")

        try:
            PyFunceble.LOGGER.info(f"Getting TXT record of {repr(subject)}")
            if reverse_name:
                # We get the reverse name we are going to request.
                to_request = dns.reversename.from_address(subject)
            else:
                to_request = subject

            # We get the PTR record of the currently read A record.
            result = [str(x) for x in self.resolver.query(to_request, "PTR", tcp=tcp)]
            PyFunceble.LOGGER.info(f"Could get PTR record of {repr(subject)}: {result}")

            return result
        except DNSException:
            PyFunceble.LOGGER.error(f"Could not get PTR record of {repr(subject)}")

        return None 
Example #10
Source File: dns.py    From PyFunceble with Apache License 2.0 5 votes vote down vote up
def txt_record(self, subject, tcp=None):
        """
        Return the TXT record of the given subject (if found).

        :param str subject: The subject we are working with.
        :param bool tcp: Tell us to use TCP for query.

        :return: A list of TXT record(s).
        :rtype: list, None
        :raise ValueError: When a non string :code:`subject` is given.
        """

        if not subject or not isinstance(subject, str):
            raise ValueError(f"<subject> must be of type {str} and not empty.")

        if tcp is None:
            tcp = self.tcp

        PyFunceble.LOGGER.debug(f"Query over TCP: {self.tcp}")

        try:
            PyFunceble.LOGGER.info(f"Getting TXT record of {repr(subject)}")
            # We get the TXT record of the given subject.
            result = [str(x) for x in self.resolver.query(subject, "TXT", tcp=tcp)]
            PyFunceble.LOGGER.info(f"Could get TXT record of {repr(subject)}: {result}")

            return result
        except DNSException:
            PyFunceble.LOGGER.error(f"Could not get TXT record of {repr(subject)}")

        return None 
Example #11
Source File: dns.py    From PyFunceble with Apache License 2.0 5 votes vote down vote up
def ns_record(self, subject, tcp=None):
        """
        Return the NS record of the given subject (if found).

        :param str subject: The subject we are working with.
        :param bool tcp: Tell us to use TCP for query.

        :return: A list of NS record(s).
        :rtype: list, None
        :raise ValueError: When a non string :code:`subject` is given.
        """

        if not subject or not isinstance(subject, str):
            raise ValueError(f"<subject> must be of type {str} and not empty.")

        if tcp is None:
            tcp = self.tcp

        PyFunceble.LOGGER.debug(f"Query over TCP: {self.tcp}")

        try:
            PyFunceble.LOGGER.info(f"Getting NS record of {repr(subject)}")
            # We get the NS record of the given subject.
            result = [str(x) for x in self.resolver.query(subject, "NS", tcp=tcp)]
            PyFunceble.LOGGER.info(f"Could get NS record of {repr(subject)}: {result}")

            return result
        except DNSException:
            PyFunceble.LOGGER.error(f"Could not get NS record of {repr(subject)}")

        return None 
Example #12
Source File: dns.py    From PyFunceble with Apache License 2.0 5 votes vote down vote up
def dname_record(self, subject, tcp=None):  # pragma: no cover
        """
        Return the DNAME record of the given subject (if found).

        :param str subject: The subject we are working with.
        :param bool tcp: Tell us to use TCP for query.

        :return: A list of DNAME record(s).
        :rtype: list, None
        :raise ValueError: When a non string :code:`subject` is given.
        """

        if not subject or not isinstance(subject, str):
            raise ValueError(f"<subject> must be of type {str} and not empty.")

        if tcp is None:
            tcp = self.tcp

        PyFunceble.LOGGER.debug(f"Query over TCP: {self.tcp}")

        try:
            PyFunceble.LOGGER.info(f"Getting DNAME record of {repr(subject)}")
            # We get the A record of the given subject.
            result = [str(x) for x in self.resolver.query(subject, "DNAME", tcp=tcp)]
            PyFunceble.LOGGER.info(
                f"Could get DNAME record of {repr(subject)}: {result}"
            )

            return result
        except DNSException:
            PyFunceble.LOGGER.error(f"Could not get DNAME record of {repr(subject)}")

        return None 
Example #13
Source File: dns.py    From PyFunceble with Apache License 2.0 5 votes vote down vote up
def cname_record(self, subject, tcp=None):
        """
        Return the CNAME record of the given subject (if found).

        :param str subject: The subject we are working with.
        :param bool tcp: Tell us to use TCP for query.

        :return: A list of CNAME record(s).
        :rtype: list, None
        :raise ValueError: When a non string :code:`subject` is given.
        """

        if not subject or not isinstance(subject, str):
            raise ValueError(f"<subject> must be of type {str} and not empty.")

        if tcp is None:
            tcp = self.tcp

        PyFunceble.LOGGER.debug(f"Query over TCP: {self.tcp}")

        try:
            PyFunceble.LOGGER.info(f"Getting CNAME record of {repr(subject)}")
            # We get the A record of the given subject.
            result = [str(x) for x in self.resolver.query(subject, "CNAME", tcp=tcp)]
            PyFunceble.LOGGER.info(
                f"Could get CNAME record of {repr(subject)}: {result}"
            )

            return result
        except DNSException:
            PyFunceble.LOGGER.error(f"Could not get CNAME record of {repr(subject)}")

        return None 
Example #14
Source File: dns.py    From PyFunceble with Apache License 2.0 5 votes vote down vote up
def aaaa_record(self, subject, tcp=None):
        """
        Return the AAAA record of the given subject (if found).

        :param str subject: The subject we are working with.
        :param bool tcp: Tell us to use TCP for query.

        :return: A list of A record(s).
        :rtype: list, None
        :raise ValueError: When a non string :code:`subject` is given.
        """

        if not subject or not isinstance(subject, str):
            raise ValueError(f"<subject> must be of type {str} and not empty.")

        if tcp is None:
            tcp = self.tcp

        PyFunceble.LOGGER.debug(f"Query over TCP: {self.tcp}")

        try:
            PyFunceble.LOGGER.info(f"Getting AAAA record of {repr(subject)}")
            # We get the A record of the given subject.
            result = [str(x) for x in self.resolver.query(subject, "AAAA", tcp=tcp)]
            PyFunceble.LOGGER.info(
                f"Could get AAAA record of {repr(subject)}: {result}"
            )

            return result
        except DNSException:
            PyFunceble.LOGGER.error(f"Could not get AAAA record of {repr(subject)}")

        return None 
Example #15
Source File: dns.py    From PyFunceble with Apache License 2.0 5 votes vote down vote up
def a_record(self, subject, tcp=None):
        """
        Return the A record of the given subject (if found).

        :param str subject: The subject we are working with.
        :param bool tcp: Tell us to use TCP for query.

        :return: A list of A record(s).
        :rtype: list, None
        :raise ValueError: When a non string :code:`subject` is given.
        """

        if not subject or not isinstance(subject, str):
            raise ValueError(f"<subject> must be of type {str} and not empty.")

        if tcp is None:
            tcp = self.tcp

        PyFunceble.LOGGER.debug(f"Query over TCP: {self.tcp}")

        try:
            PyFunceble.LOGGER.info(f"Getting A record of {repr(subject)}")
            # We get the A record of the given subject.
            result = [str(x) for x in self.resolver.query(subject, "A", tcp=tcp)]
            PyFunceble.LOGGER.info(f"Could get A record of {repr(subject)}: {result}")

            return result
        except DNSException:
            PyFunceble.LOGGER.error(f"Could not get A record of {repr(subject)}")

        return None 
Example #16
Source File: dns.py    From PyFunceble with Apache License 2.0 5 votes vote down vote up
def __get_dns_servers_from(self, inputed_dns):  # pragma: no cover
        """
        Given a list or an input representing dns servers,
        we ensure that we have a list of a string which
        represent an IP.

        :param input: The inputed DNS server(s).
        :type input: str, list, tuple

        :return: The list of dns server to use.
        :rtype: list
        """

        if isinstance(inputed_dns, (list, tuple)):
            result = []
            for dns_server in inputed_dns:
                result.extend(self.__get_dns_servers_from(dns_server))

            return result

        result = []

        try:
            if PyFunceble.Check(inputed_dns).is_domain():
                result.extend(
                    [x.address for x in dns.resolver.Resolver().query(inputed_dns)]
                )
            else:
                result.append(inputed_dns)
        except DNSException:
            result.extend(dns.resolver.get_default_resolver().nameservers)

        return result 
Example #17
Source File: test_etcd.py    From patroni with MIT License 5 votes vote down vote up
def dns_query(name, _):
    if '-server' not in name or '-ssl' in name:
        return []
    if name == '_etcd-server._tcp.blabla':
        return []
    elif name == '_etcd-server._tcp.exception':
        raise DNSException()
    srv = Mock()
    srv.port = 2380
    srv.target.to_text.return_value = 'localhost' if name == '_etcd-server._tcp.foobar' else '127.0.0.1'
    return [srv] 
Example #18
Source File: network.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def _a_lookup(name: str) -> List[str]:
    try:
        return [e.address for e in resolver.query(name, 'A')]
    except DNSException:
        return [] 
Example #19
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 #20
Source File: dockerDDNS.py    From docker-tools with MIT License 5 votes vote down vote up
def remove_container(container_id):
    logging.info("Destroying %s", container_id)
    short_id = container_id[:12]
    record_to_delete = [short_id]
    logging.debug("Looking for alias to %s.%s", short_id, args.domain)

    try:
        answers = resolver.query("{0}.{1}.".format(short_id, args.domain), "TXT", raise_on_no_answer=False).rrset
        if answers:
            for answer in answers:
                logging.debug("Checking TXT record %s for alias", answer)
                match = re.search(r"dockerDDNS-alias:([^:]+):", answer.to_text())
                if match:
                    record_to_delete.append(match.group(1))
    except DNSException as e:
        logging.error("Cannot get TXT record for %s: %s", short_id, e)
    except:
        logging.error("Unexpected error: %s", sys.exc_info()[0])
        raise

    if not args.dry_run:
        nsupdate = Popen(['nsupdate', '-k', args.key], stdin=PIPE)
        nsupdate.stdin.write(bytes(zone_update_start_template.format(args.server, args.zone), "UTF-8"))

        for record in record_to_delete:
            logging.info("Removing record for %s", record)
            nsupdate.stdin.write(bytes(zone_update_delete_record_template.format(record, args.domain), "UTF-8"))

        nsupdate.stdin.write(bytes("send\n", "UTF-8"))
        nsupdate.stdin.close() 
Example #21
Source File: update-zonefile.py    From bind-adblock with MIT License 5 votes vote down vote up
def check_domain(domain, origin):
    if domain == '':
        return False

    if config['wildcard_block']:
        domain = '*.' + domain

    try:
        name = dns.name.from_text(domain, origin)
    except DNSException as e:
        return False

    return True 
Example #22
Source File: test_enrich.py    From n6 with GNU Affero General Public License v3.0 5 votes vote down vote up
def test__enrich__with_fqdn_from_url_not_resolved(self):
        self.enricher._resolver.query = mock.MagicMock(side_effect=DNSException)
        data = self.enricher.enrich(RecordDict({"url": "http://www.nask.pl/asd"}))
        self.assertEqualIncludingTypes(data, RecordDict({
            "enriched": (["fqdn"], {}),
            "url": "http://www.nask.pl/asd",
            "fqdn": "www.nask.pl"})) 
Example #23
Source File: test_enrich.py    From n6 with GNU Affero General Public License v3.0 5 votes vote down vote up
def test__enrich__with_fqdn_not_resolved(self):
        self.enricher._resolver.query = mock.MagicMock(side_effect=DNSException)
        data = self.enricher.enrich(RecordDict({"fqdn": "cert.pl"}))
        self.assertEqualIncludingTypes(data, RecordDict({
            "enriched": ([], {}),
            "fqdn": "cert.pl"})) 
Example #24
Source File: enrich.py    From n6 with GNU Affero General Public License v3.0 5 votes vote down vote up
def fqdn_to_ip(self, fqdn):
        try:
            dns_result = self._resolver.query(fqdn, 'A')
        except DNSException:
            return []
        ip_set = set()
        for i in dns_result:
            ip_set.add(str(i))
        return sorted(ip_set) 
Example #25
Source File: axfr.py    From octodns with MIT License 5 votes vote down vote up
def _load_zone_file(self, zone_name):
        zonefiles = listdir(self.directory)
        if zone_name in zonefiles:
            try:
                z = dns.zone.from_file(join(self.directory, zone_name),
                                       zone_name, relativize=False,
                                       check_origin=self.check_origin)
            except DNSException as error:
                raise ZoneFileSourceLoadFailure(error)
        else:
            raise ZoneFileSourceNotFound()

        return z 
Example #26
Source File: network.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def _reverse_lookup(ip: str) -> List[str]:
    try:
        address = reversename.from_address(ip).to_text()
        return [rev.to_text()[:-1].lower()
                for rev in resolver.query(address, 'PTR')]
    except DNSException:
        return [] 
Example #27
Source File: network.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def _mx_lookup(name: str) -> List[str]:
    try:
        return sorted([(e.preference, e.exchange.to_text()[:-1].lower())
                       for e in resolver.query(name, 'MX')], key=lambda v: v[0])
    except DNSException:
        return [] 
Example #28
Source File: network.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def _cname_lookup(name: str) -> List[str]:
    try:
        return [e.to_text()[:-1].lower() for e in resolver.query(name, 'CNAME')]
    except DNSException:
        return []