Python dns.exception.Timeout() Examples

The following are 9 code examples of dns.exception.Timeout(). 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: subdomain-analyzer.py    From SubDomain-Analyzer with GNU General Public License v3.0 6 votes vote down vote up
def analyze_domain(self, host):
        '''
            This function is responsible to recieve IP from domain and appends to the report
            if the ip not exists on `OCT_LIST` variable, he append the IP to the `async_ip_analyzer` function
        '''
        try:
            domain = '{host}.{url}'.format(host=host.rstrip('.'), url=self.root_domain) # Create a subdomain to check, example: host=www, url=example.com
            answer = dns.resolver.query(domain, "A") # returns IP from domain
            for data in answer:
                ip = data.address
                REPORT_DETAILS[domain].add(ip)
                oct_ip = self.__oct_builder(ip)
                if self.__is_public(ip) and oct_ip not in OCT_LIST: # Checks if the ip is a public address, and the IP will not exists on the `OCTLIST` variable,
                    self.async_ip_analyzer(ip)
            self.logger.info("[Domain Analyzer] %s exists" % domain)
        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers, Timeout, TypeError):
            pass
        except Exception as e:
            self.logger.exception("[Domain Analyzer][Error] %s" % e.message) 
Example #2
Source File: models.py    From desec-stack with MIT License 5 votes vote down vote up
def public_suffix(self):
        try:
            public_suffix = psl.get_public_suffix(self.name)
            is_public_suffix = psl.is_public_suffix(self.name)
        except (Timeout, NoNameservers):
            public_suffix = self.name.rpartition('.')[2]
            is_public_suffix = ('.' not in self.name)  # TLDs are public suffixes
        except psl_dns.exceptions.UnsupportedRule as e:
            # It would probably be fine to treat this as a non-public suffix (with the TLD acting as the
            # public suffix and setting both public_suffix and is_public_suffix accordingly).
            # However, in order to allow to investigate the situation, it's better not catch
            # this exception. For web requests, our error handler turns it into a 503 error
            # and makes sure admins are notified.
            raise e

        if is_public_suffix:
            return public_suffix

        # Take into account that any of the parent domains could be a local public suffix. To that
        # end, identify the longest local public suffix that is actually a suffix of domain_name.
        for local_public_suffix in settings.LOCAL_PUBLIC_SUFFIXES:
            has_local_public_suffix_parent = ('.' + self.name).endswith('.' + local_public_suffix)
            if has_local_public_suffix_parent and len(local_public_suffix) > len(public_suffix):
                public_suffix = local_public_suffix

        return public_suffix 
Example #3
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 #4
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 #5
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 #6
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 #7
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 #8
Source File: subdomain-analyzer.py    From SubDomain-Analyzer with GNU General Public License v3.0 5 votes vote down vote up
def zone_transfer(logger, url):
        '''
            This function is responsible to try to get the `zone transfer` file.
            If he success, he shows the `zone transfer` file and he will finish.

            How this function works?
            he get all the DNS Records and try to get the `zone transfer` file by all the records.
            If he failed, he will continue to try to get the `zone transfer file` by the next DNS record.
            If all the records will fail, we cant to get a `zone transfer` file.
            The function will returns false value.
        '''
        try:
            logger.info("[DNS] Trying zone transfer first..")
            answers = resolver.query(url, 'NS')
            for ns in (ns.to_text().rstrip('.') for ns in answers):
                try:
                    z = zone.from_xfr(
                        query.xfr(ns, url)
                    )
                    zone_record = "\n".join(z[z_node].to_text(z_node) for z_node in z.nodes.keys())
                    logger.info("[DNS] Zone file:!\n%s" % zone_record)
                    return True
                except socket.error:
                    pass
        except (FormError, dns.resolver.NoAnswer, dns.exception.Timeout, EOFError):
            pass
        except Exception as e:
            logger.error('[DNS][Error] %s' % e.message)
        return False 
Example #9
Source File: host.py    From Raccoon with MIT License 4 votes vote down vote up
def parse(self):
        """
        Try to extract domain (full, naked, sub-domain), IP and port.
        """
        if self.target.endswith("/"):
            self.target = self.target[:-1]

        if self._is_proto(self.target):
            try:
                self.protocol, self.target = self.target.split("://")
                self.logger.info("{} Protocol detected: {}".format(COLORED_COMBOS.NOTIFY, self.protocol))
                if self.protocol.lower() == "https" and self.port == 80:
                    self.port = 443
            except ValueError:
                raise HostHandlerException("Could not make domain and protocol from host")

        if ":" in self.target:
            self._extract_port(self.target)

        if self.validate_ip(self.target):
            self.logger.info("{} Detected {} as an IP address.".format(COLORED_COMBOS.NOTIFY, self.target))
            self.is_ip = True
        else:
            domains = []
            if self.target.startswith("www."):
                # Obviously an FQDN
                domains.extend((self.target, self.target.split("www.")[1]))
                self.fqdn = self.target
                self.naked = ".".join(self.fqdn.split('.')[1:])
            else:
                domains.append(self.target)
                domain_levels = self.target.split(".")
                if len(domain_levels) == 2 or (len(domain_levels) == 3 and domain_levels[1] == "co"):
                    self.logger.info("{} Found {} to be a naked domain".format(COLORED_COMBOS.NOTIFY, self.target))
                    self.naked = self.target

            try:
                self.dns_results = DNSHandler.query_dns(domains, self.dns_records)
            except Timeout:
                raise HostHandlerException("DNS Query timed out. Maybe target has DNS protection ?")

            if self.dns_results.get("CNAME"):
                # Naked domains shouldn't hold CNAME records according to RFC regulations
                self.logger.info("{} Found {} to be an FQDN by CNAME presence in DNS records".format(
                    COLORED_COMBOS.NOTIFY, self.target))

                self.fqdn = self.target
                self.naked = ".".join(self.fqdn.split('.')[1:])
        self.create_host_dir_and_set_file_logger()
        self.write_up()