Python dns.resolver.lifetime() Examples

The following are 29 code examples of dns.resolver.lifetime(). 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: blockcheck.py    From blockcheck with MIT License 7 votes vote down vote up
def _get_a_record(site, querytype='A', dnsserver=None):
    resolver = dns.resolver.Resolver()
    resolver.timeout = 5
    resolver.lifetime = 5

    if dnsserver:
        resolver.nameservers = [dnsserver]

    result = []
    while len(resolver.nameservers):
        try:
            resolved = resolver.query(site, querytype)
            print_debug(str(resolved.response))
            for item in resolved.rrset.items:
                result.append(item.to_text())
            return result

        except dns.exception.Timeout:
            print_debug("DNS Timeout for", site, "using", resolver.nameservers[0])
            resolver.nameservers.remove(resolver.nameservers[0])

    # If all the requests failed
    return "" 
Example #2
Source File: email_hacker.py    From email_hack with MIT License 6 votes vote down vote up
def DNSQuery(to_addr):
    resolver = dns.resolver.Resolver()
    resolver.timeout = 3
    resolver.lifetime = 3

    Print(u"query MX of DNS for %s" % to_addr, sign=u"[+]")

    try:
        SMTP_addr = b'.'.join(dns.resolver.query(
            to_addr[to_addr.find(u"@")+1:], u'MX')[0].exchange.labels).decode(u"utf8")
        assert SMTP_addr != u""
    except Exception as e:
        Print(u"query MX of %s failed: " % to_addr + str(e),
              threshold=0, color=u"red", sign=u"[X]", flag=0)
        return 0

    Print(u"success", sign=u"  [*]")
    return SMTP_addr 
Example #3
Source File: resolver.py    From blacklist-rkn-tool with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, cfg, transact, reporter, code_id):
        logger.info('Resolver init')
        self.code_id = code_id
        self.transact = transact
        self.cfg = cfg
        self.reporter = reporter
        self.domain_sql = self.reporter.domain_rollback_sql(0, 'ignore')

        self.dns_servers = str(cfg.DNS()).split(' ')
        self.resolvers = [dns.resolver.Resolver(configure=False) for i in range(len(self.dns_servers))]
        for resolver, dns_server in zip(self.resolvers, self.dns_servers):
            resolver.nameservers = [dns_server]
            resolver.timeout = self.cfg.QueryTimeout()
            resolver.lifetime = self.cfg.QueryTimeout()

        logger.info('Resolver history.id: %s', self.code_id) 
Example #4
Source File: subDomainsBrute.py    From ZeroScan with MIT License 6 votes vote down vote up
def _test_server(self, server):
        resolver = dns.resolver.Resolver()
        resolver.lifetime = resolver.timeout = 10.0
        try:
            resolver.nameservers = [server]
            answers = resolver.query('public-dns-a.baidu.com')    # test lookup a existed domain
            if answers[0].address != '180.76.76.76':
                raise Exception('incorrect DNS response')
            try:
                resolver.query('test.bad.dns.lijiejie.com')    # Non-existed domain test
                with open('bad_dns_servers.txt', 'a') as f:
                    f.write(server + '\n')
                self._print_msg('[+] Bad DNS Server found %s' % server)
            except:
                self.dns_servers.append(server)
            self._print_msg('[+] Check DNS Server %s < OK >   Found %s' % (server.ljust(16), len(self.dns_servers)))
        except:
            self._print_msg('[+] Check DNS Server %s <Fail>   Found %s' % (server.ljust(16), len(self.dns_servers))) 
Example #5
Source File: dnask.py    From cyber-security-framework with MIT License 6 votes vote down vote up
def run(self):
        arguments = self.arguments.__dict__
        nameservers = arguments.get("nameservers")
        resolver = dns.resolver.Resolver(arguments.get("filename"), arguments.get("configure_resolver"))
        resolver.set_flags(arguments.get("flags"))
        resolver.use_edns(arguments.get("edns"), arguments.get("edns_flags"), arguments.get("edns_payload"))
        if nameservers:
            resolver.nameservers = nameservers
        resolver.port = arguments.get("port")
        resolver.timeout = arguments.get("timeout")
        resolver.lifetime = arguments.get("lifetime")
        resolver.retry_servfail = arguments.get("retry_servfail")
        if arguments.pop("metaquery"):
            kwargs = {v: arguments.get(k) for k, v in {"rdclass": "rdclass", "edns": "use_edns", "want_dnssec": "want_dnssec", "edns_flags": "ednsflags", "edns_payload": "request_payload"}.items()}
            message = dns.message.make_query(arguments.get("query"), arguments.get("rdtype"), **kwargs)
            kwargs = {k: arguments.get(k) for k in ["timeout", "port", "source", "source_port", "one_rr_per_rrset"]}
            if arguments.get("tcp"):
                resp = dns.query.tcp(message, resolver.nameservers[0], **kwargs)
            else:
                resp = dns.query.udp(message, resolver.nameservers[0], **kwargs)
            print(resp)
        else:
            kwargs = {k: arguments.get(k) for k in ["rdtype", "rdclass", "tcp", "source", "source_port"]}
            answer = resolver.query(arguments.pop("query"), **kwargs)
            print(answer.response) 
Example #6
Source File: dnask.py    From cyber-security-framework with MIT License 6 votes vote down vote up
def __init__(self):
        super().__init__()
        self.parser.add_argument("query", type=str, help="Query string.")
        self.parser.add_argument("-t", "--rdtype", type=str, default=1, help="Query type.")
        self.parser.add_argument("-c", "--rdclass", type=str, default=1, help="Query class.")
        self.parser.add_argument("-m", "--metaquery", action="store_true", help="Execute as MetaQuery.")
        self.parser.add_argument("-s", "--source", type=str, default=socket.gethostbyname(socket.gethostname()), help="Source address.")
        self.parser.add_argument("-sP", "--source-port", type=int, default=random.randint(1, 65535), help="Source port.")
        self.parser.add_argument("--tcp", action="store_true", help="Use TCP to make the query.")
        self.parser.add_argument("-ns", "--nameservers", nargs="+", type=str, help="A list of nameservers to query. Each nameserver is a string which contains the IP address of a nameserver.")
        self.parser.add_argument("-p", "--port", type=int, default=53, help="The port to which to send queries (Defaults to 53).")
        self.parser.add_argument("-T", "--timeout", type=int, default=8, help="The number of seconds to wait for a response from a server, before timing out.")
        self.parser.add_argument("-l", "--lifetime", type=int, default=8, help="The total number of seconds to spend trying to get an answer to the question. If the lifetime expires, a Timeout exception will occur.")
        self.parser.add_argument("-e", "--edns", type=int, default=-1, help="The EDNS level to use (Defaults to -1, no Edns).")
        self.parser.add_argument("-eF", "--edns-flags", type=int, help="The EDNS flags.")
        self.parser.add_argument("-eP", "--edns-payload", type=int, default=0, help="The EDNS payload size (Defaults to 0).")
        self.parser.add_argument("-S", "--want-dnssec", action="store_true", help="Indicate that DNSSEC is desired.")
        self.parser.add_argument("-f", "--flags", type=int, default=None, help="The message flags to use (Defaults to None (i.e. not overwritten)).")
        self.parser.add_argument("-r", "--retry-servfail", action="store_true", help="Retry a nameserver if it says SERVFAIL.")
        self.parser.add_argument("-R", "--one-rr-per-rrset", action="store_true", help="Put each RR into its own RRset (Only useful when executing MetaQueries).")
        self.parser.add_argument("--filename", type=argparse.FileType("r"), help="The filename of a configuration file in standard /etc/resolv.conf format. This parameter is meaningful only when I{configure} is true and the platform is POSIX.")
        self.parser.add_argument("--configure-resolver", action="store_false", help="If True (the default), the resolver instance is configured in the normal fashion for the operating system the resolver is running on. (I.e. a /etc/resolv.conf file on POSIX systems and from the registry on Windows systems.") 
Example #7
Source File: Email.py    From email_hack with MIT License 6 votes vote down vote up
def DNSQuery(self):
        resolver = dns.resolver.Resolver()
        resolver.timeout = 3
        resolver.lifetime = 3

        try:
            host = self.to_addr[self.to_addr.find(u"@")+1:]

            # dns 列表
            self.SMTP_addrs = [b'.'.join(d.exchange.labels).decode(u"utf8") for d in dns.resolver.query(host, u'MX')]
            assert len(self.SMTP_addrs) > 1  # 确保 dns 有结果

        except Exception as e:
            return (False, u"get MX record of %s failed: " % self.to_addr + str(e))

        return (True, u"get MX record of %s success" % host) 
Example #8
Source File: Unstable_version.py    From email_hack with MIT License 6 votes vote down vote up
def DNSQuery(to_addr):
    resolver = dns.resolver.Resolver()
    resolver.timeout = 3
    resolver.lifetime = 3

    Print(u"query MX of DNS for %s" % to_addr, sign=u"[+]")

    try:
        SMTP_addr = b'.'.join(dns.resolver.query(
            to_addr[to_addr.find(u"@")+1:], u'MX')[0].exchange.labels).decode(u"utf8")
        assert SMTP_addr != u""
    except Exception as e:
        Print(u"query MX of %s failed: " % to_addr + str(e),
              threshold=0, color=u"red", sign=u"[X]", flag=0)
        return 0

    Print(u"success", sign=u"  [*]")
    return SMTP_addr 
Example #9
Source File: email_hacker-GUI.py    From email_hack with MIT License 6 votes vote down vote up
def DNSQuery(to_addr):
    resolver = dns.resolver.Resolver()
    resolver.timeout = 3
    resolver.lifetime = 3

    Print(u"query MX of DNS for %s" % to_addr, sign=u"[+]")

    try:
        SMTP_addr = b'.'.join(dns.resolver.query(
            to_addr[to_addr.find(u"@")+1:], u'MX')[0].exchange.labels).decode(u"utf8")
        assert SMTP_addr != u""
    except Exception as e:
        Print(u"query MX of %s failed: " % to_addr + str(e),
              threshold=0, color=u"red", sign=u"[X]", flag=0)
        return 0

    Print(u"success", sign=u"  [*]")
    return SMTP_addr 
Example #10
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 #11
Source File: dns-queue.py    From dns-parallel-prober with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        resolver = dns.resolver.Resolver()
        resolver.timeout = self.dns_timeout
        # as per http://comments.gmane.org/gmane.comp.python.dnspython.user/144
        resolver.lifetime = self.dns_timeout
        try:
            log.debug("{}: Resolving {} with nameserver {}".format(
                self.name, self.target, self.dns_server))
            # it's a list
            resolver.nameservers = [self.dns_server, ]
            answer = resolver.query(self.target)
            for data in answer:
                out = '{} | {}'.format(self.target, data)
                self.res.append(out)
                # don't log to console, use file.
                # log.info(out)
        except dns.exception.Timeout as e:
            # we want to know if the DNS server is barfing
            errmsg = "{}: {}".format(self.target, e)
            self.err.append(errmsg)
            # log.warn(errmsg)
        except dns.exception.DNSException as e:
            log.debug("Error in thread {} when querying {}: {}".format(
                self.name, self.target, e)) 
Example #12
Source File: get_domain_ip.py    From armory with GNU General Public License v3.0 6 votes vote down vote up
def run(domain):
    ips = []
    resolver = dns.resolver.Resolver()
    resolver.lifetime = resolver.timeout = 5.0

    try:
        answers = resolver.query(domain, "A")
        for a in answers:
            ips.append(a.address)
        return ips
    except Exception:
        # print("Regular DNS Not Resolved\n")
    # Temporarily disabling - seems to cause massive delays at times.

    #     pass
    # try:
    #    ips = [ str(i[4][0]) for i in socket.getaddrinfo(domain, 443) ] 
    #    return ips
    # except Exception:
    #    print("Unable to Resolve\n")
       return ips 
Example #13
Source File: subbrute.py    From Horn3t with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, target, record_type, resolver_q, resolver_list, wildcards):
        multiprocessing.Process.__init__(self, target = self.run)
        self.daemon = True
        signal_init()

        self.time_to_die = False
        self.resolver_q = resolver_q
        self.wildcards = wildcards
        #Do we need wildcards for other types of records?
        #This needs testing!
        self.record_type = "A"
        if record_type == "AAAA":
            self.record_type = record_type
        self.resolver_list = resolver_list
        resolver = dns.resolver.Resolver()
        #The domain provided by the user.
        self.target = target
        #1 website in the world,  modify the following line when this status changes.
        #www.google.cn,  I'm looking at you ;)
        self.most_popular_website = "www.google.com"
        #We shouldn't need the backup_resolver, but we we can use them if need be.
        #We must have a resolver,  and localhost can work in some environments.
        self.backup_resolver = resolver.nameservers + ['127.0.0.1', '8.8.8.8', '8.8.4.4']
        #Ideally a nameserver should respond in less than 1 sec.
        resolver.timeout = 1
        resolver.lifetime = 1
        try:
            #Lets test the letancy of our connection.
            #Google's DNS server should be an ideal time test.
            resolver.nameservers = ['8.8.8.8']
            resolver.query(self.most_popular_website, self.record_type)
        except:
            #Our connection is slower than a junebug in molasses
            resolver = dns.resolver.Resolver()
        self.resolver = resolver 
Example #14
Source File: __init__.py    From dnsbrute with MIT License 5 votes vote down vote up
def query(self, name, query_type):
        """
        Perform a DNS query for the DNS `name`, of `query_type` (e.g. A, AAAA)
        """
        resolver = dns.resolver.Resolver()
        resolver.timeout = self.options.timeout
        resolver.lifetime = self.options.timeout * self.options.retries
        # N random nameservers are chosen from the list
        sample_size = self.options.retries * 3
        resolver.nameservers = random.sample(self.resolvers, sample_size)
        resolver.rotate = True
        return resolver.query(name, rdtype=query_type) 
Example #15
Source File: hook.py    From letsencrypt-ovh-hook with MIT License 5 votes vote down vote up
def check_if_record_is_deployed(domain, dns_record, token):
    """
    Retrieve names servers of the domain, and check DNS record presence.
    """
    dns_servers = dns.resolver.query(domain, 'NS')
    resolver = dns.resolver.Resolver()
    resolver.nameservers = []
    resolver.timeout = 3
    resolver.lifetime = 5
    for dns_server in dns_servers:
        addresses = socket.getaddrinfo(dns_server.to_text(), 53, 0, 0, socket.IPPROTO_TCP)
        for family, socktype, proto, canonname, sockaddr in addresses:
            resolver.nameservers.append(sockaddr[0])
    while True:
        logger.debug(" + Testing DNS record against %s", ', '.join(resolver.nameservers))
        txt_values = []
        try:
            txt_records = resolver.query('{}.{}'.format(dns_record, domain), 'TXT')
            for txt_record in txt_records:
                txt_values.append(txt_record.to_text())
            for txt_value in txt_values:
                if token in txt_value:
                    return
        except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
            logger.debug(" + Record not available yet. Checking again in 10s...")
        except dns.exception.Timeout:
            logger.debug(" + DNS Request timeout. Checking again in 10s...")
        logger.debug(" + %s DNS entry value: %s ; expecting: '%s'", dns_record, ', '.join(txt_values), token)
        time.sleep(10) 
Example #16
Source File: subbrute.py    From BillCipher with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, target, record_type, resolver_q, resolver_list, wildcards):
        multiprocessing.Process.__init__(self, target = self.run)
        self.daemon = True
        signal_init()

        self.time_to_die = False
        self.resolver_q = resolver_q
        self.wildcards = wildcards
        #Do we need wildcards for other types of records?
        #This needs testing!
        self.record_type = "A"
        if record_type == "AAAA":
            self.record_type = record_type
        self.resolver_list = resolver_list
        resolver = dns.resolver.Resolver()
        #The domain provided by the user.
        self.target = target
        #1 website in the world,  modify the following line when this status changes.
        #www.google.cn,  I'm looking at you ;)
        self.most_popular_website = "www.google.com"
        #We shouldn't need the backup_resolver, but we we can use them if need be.
        #We must have a resolver,  and localhost can work in some environments.
        self.backup_resolver = resolver.nameservers + ['127.0.0.1', '8.8.8.8', '8.8.4.4']
        #Ideally a nameserver should respond in less than 1 sec.
        resolver.timeout = 1
        resolver.lifetime = 1
        try:
            #Lets test the letancy of our connection.
            #Google's DNS server should be an ideal time test.
            resolver.nameservers = ['8.8.8.8']
            resolver.query(self.most_popular_website, self.record_type)
        except:
            #Our connection is slower than a junebug in molasses
            resolver = dns.resolver.Resolver()
        self.resolver = resolver 
Example #17
Source File: subbrute.py    From Sublist3r with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, target, record_type, resolver_q, resolver_list, wildcards):
        multiprocessing.Process.__init__(self, target = self.run)
        self.daemon = True
        signal_init()

        self.time_to_die = False
        self.resolver_q = resolver_q
        self.wildcards = wildcards
        #Do we need wildcards for other types of records?
        #This needs testing!
        self.record_type = "A"
        if record_type == "AAAA":
            self.record_type = record_type
        self.resolver_list = resolver_list
        resolver = dns.resolver.Resolver()
        #The domain provided by the user.
        self.target = target
        #1 website in the world,  modify the following line when this status changes.
        #www.google.cn,  I'm looking at you ;)
        self.most_popular_website = "www.google.com"
        #We shouldn't need the backup_resolver, but we we can use them if need be.
        #We must have a resolver,  and localhost can work in some environments.
        self.backup_resolver = resolver.nameservers + ['127.0.0.1', '8.8.8.8', '8.8.4.4']
        #Ideally a nameserver should respond in less than 1 sec.
        resolver.timeout = 1
        resolver.lifetime = 1
        try:
            #Lets test the letancy of our connection.
            #Google's DNS server should be an ideal time test.
            resolver.nameservers = ['8.8.8.8']
            resolver.query(self.most_popular_website, self.record_type)
        except:
            #Our connection is slower than a junebug in molasses
            resolver = dns.resolver.Resolver()
        self.resolver = resolver 
Example #18
Source File: subDomainsBrute.py    From ZeroScan with MIT License 5 votes vote down vote up
def __init__(self, target, options):
        self.start_time = time.time()
        self.target = target.strip()
        self.options = options
        self.ignore_intranet = options.i
        self.scan_count = self.found_count = 0
        self.console_width = getTerminalSize()[0] - 2
        self.resolvers = [dns.resolver.Resolver(configure=False) for _ in range(options.threads)]
        for _ in self.resolvers:
            _.lifetime = _.timeout = 10.0
        self.print_count = 0
        self.STOP_ME = False
        self._load_dns_servers()
        self._load_next_sub()
        self.queue = PriorityQueue()
        self.priority = 0
        self._load_sub_names()
        if options.output:
            outfile = options.output
        else:
            _name = os.path.basename(self.options.file).replace('subnames', '')
            if _name != '.txt':
                _name = '_' + _name
            outfile = target + _name if not options.full_scan else target + '_full' + _name
        self.outfile = open(outfile, 'w')
        self.ip_dict = {}
        self.found_subs = set()
        self.ex_resolver = dns.resolver.Resolver(configure=False)
        self.ex_resolver.nameservers = self.dns_servers 
Example #19
Source File: subbrute.py    From subtake with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, target, record_type, resolver_q, resolver_list, wildcards):
        multiprocessing.Process.__init__(self, target = self.run)
        self.daemon = True
        signal_init()

        self.time_to_die = False
        self.resolver_q = resolver_q
        self.wildcards = wildcards
        #Do we need wildcards for other types of records?
        #This needs testing!
        self.record_type = "A"
        if record_type == "AAAA":
            self.record_type = record_type
        self.resolver_list = resolver_list
        resolver = dns.resolver.Resolver()
        #The domain provided by the user.
        self.target = target
        #1 website in the world,  modify the following line when this status changes.
        #www.google.cn,  I'm looking at you ;)
        self.most_popular_website = "www.google.com"
        #We shouldn't need the backup_resolver, but we we can use them if need be.
        #We must have a resolver,  and localhost can work in some environments.
        self.backup_resolver = resolver.nameservers + ['127.0.0.1', '8.8.8.8', '8.8.4.4']
        #Ideally a nameserver should respond in less than 1 sec.
        resolver.timeout = 1
        resolver.lifetime = 1
        try:
            #Lets test the letancy of our connection.
            #Google's DNS server should be an ideal time test.
            resolver.nameservers = ['8.8.8.8']
            resolver.query(self.most_popular_website, self.record_type)
        except:
            #Our connection is slower than a junebug in molasses
            resolver = dns.resolver.Resolver()
        self.resolver = resolver 
Example #20
Source File: privdns.py    From privdns with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_resolver(nameserver):
    resolver = dns.resolver.Resolver()
    resolver.nameservers = [nameserver]
    resolver.timeout = args.timeout
    resolver.lifetime = args.timeout
    return resolver

# argparse 
Example #21
Source File: psdns.py    From pscheduler with Apache License 2.0 5 votes vote down vote up
def dns_resolve(host,
                query=None,
                ip_version=4,
                timeout=__DEFAULT_TIMEOUT__
                ):
    """
    Resolve a hostname to its A record, returning None if not found or
    there was a timeout.
    """
    __check_ip_version__(ip_version)

    if query is None:

        # The default query is for a host,

        return __dns_resolve_host(host, ip_version, timeout)

    else:

        # Any other explicit query value is forced to use DNS.

        try:
            resolver = dns.resolver.Resolver()
            resolver.timeout = timeout
            resolver.lifetime = timeout
            if query is None:
                query = 'A' if ip_version == 4 else 'AAAA'
            answers = resolver.query(host, query)
        except (dns.exception.Timeout,
                dns.name.EmptyLabel,
                dns.resolver.NXDOMAIN,
                dns.resolver.NoAnswer,
                dns.resolver.NoNameservers):
            return None

        return str(answers[0]) 
Example #22
Source File: subbrute.py    From ITWSV with MIT License 5 votes vote down vote up
def __init__(self, target, record_type, resolver_q, resolver_list, wildcards):
        multiprocessing.Process.__init__(self, target = self.run)
        self.daemon = True
        signal_init()

        self.time_to_die = False
        self.resolver_q = resolver_q
        self.wildcards = wildcards
        #Do we need wildcards for other types of records?
        #This needs testing!
        self.record_type = "A"
        if record_type == "AAAA":
            self.record_type = record_type
        self.resolver_list = resolver_list
        resolver = dns.resolver.Resolver()
        #The domain provided by the user.
        self.target = target
        #1 website in the world,  modify the following line when this status changes.
        #www.google.cn,  I'm looking at you ;)
        self.most_popular_website = "www.google.com"
        #We shouldn't need the backup_resolver, but we we can use them if need be.
        #We must have a resolver,  and localhost can work in some environments.
        self.backup_resolver = resolver.nameservers + ['127.0.0.1', '8.8.8.8', '8.8.4.4']
        #Ideally a nameserver should respond in less than 1 sec.
        resolver.timeout = 1
        resolver.lifetime = 1
        try:
            #Lets test the letancy of our connection.
            #Google's DNS server should be an ideal time test.
            resolver.nameservers = ['8.8.8.8']
            resolver.query(self.most_popular_website, self.record_type)
        except:
            #Our connection is slower than a junebug in molasses
            resolver = dns.resolver.Resolver()
        self.resolver = resolver 
Example #23
Source File: networking_test.py    From designate with Apache License 2.0 5 votes vote down vote up
def _setup_resolver(self, timeout=1):
        resolver = dns.resolver.Resolver(configure=False)
        resolver.timeout = timeout
        resolver.lifetime = timeout
        resolver.nameservers = [self.ns_ipaddr]
        self.resolver = resolver 
Example #24
Source File: subbrute.py    From Yuki-Chan-The-Auto-Pentest with MIT License 5 votes vote down vote up
def __init__(self, target, record_type, resolver_q, resolver_list, wildcards):
        multiprocessing.Process.__init__(self, target = self.run)
        self.daemon = True
        signal_init()

        self.time_to_die = False
        self.resolver_q = resolver_q
        self.wildcards = wildcards
        #Do we need wildcards for other types of records?
        #This needs testing!
        self.record_type = "A"
        if record_type == "AAAA":
            self.record_type = record_type
        self.resolver_list = resolver_list
        resolver = dns.resolver.Resolver()
        #The domain provided by the user.
        self.target = target
        #1 website in the world,  modify the following line when this status changes.
        #www.google.cn,  I'm looking at you ;)
        self.most_popular_website = "www.google.com"
        #We shouldn't need the backup_resolver, but we we can use them if need be.
        #We must have a resolver,  and localhost can work in some environments.
        self.backup_resolver = resolver.nameservers + ['127.0.0.1', '8.8.8.8', '8.8.4.4']
        #Ideally a nameserver should respond in less than 1 sec.
        resolver.timeout = 1
        resolver.lifetime = 1
        try:
            #Lets test the letancy of our connection.
            #Google's DNS server should be an ideal time test.
            resolver.nameservers = ['8.8.8.8']
            resolver.query(self.most_popular_website, self.record_type)
        except:
            #Our connection is slower than a junebug in molasses
            resolver = dns.resolver.Resolver()
        self.resolver = resolver 
Example #25
Source File: Mail.py    From AIL-framework with GNU Affero General Public License v3.0 4 votes vote down vote up
def check_mx_record(set_mxdomains, dns_server):
    """Check if emails MX domains are responding.

    :param adress_set: -- (set) This is a set of emails domains
    :return: (int) Number of adress with a responding and valid MX domains

    """
    resolver = dns.resolver.Resolver()
    resolver.nameservers = [dns_server]
    resolver.timeout = 5.0
    resolver.lifetime = 2.0

    valid_mxdomain = []
    for mxdomain in set_mxdomains:

        # check if is in cache
        # # TODO:
        if is_mxdomain_in_cache(mxdomain):
            valid_mxdomain.append(mxdomain)
        else:

            # DNS resolution
            try:
                answers = resolver.query(mxdomain, rdtype=dns.rdatatype.MX)
                if answers:
                    save_mxdomain_in_cache(mxdomain)
                    valid_mxdomain.append(mxdomain)
                    # DEBUG
                    # print('---')
                    # print(answers.response)
                    # print(answers.qname)
                    # print(answers.rdtype)
                    # print(answers.rdclass)
                    # print(answers.nameserver)
                    # print()

            except dns.resolver.NoNameservers:
                publisher.debug('NoNameserver, No non-broken nameservers are available to answer the query.')
                print('NoNameserver, No non-broken nameservers are available to answer the query.')
            except dns.resolver.NoAnswer:
                publisher.debug('NoAnswer, The response did not contain an answer to the question.')
                print('NoAnswer, The response did not contain an answer to the question.')
            except dns.name.EmptyLabel:
                publisher.debug('SyntaxError: EmptyLabel')
                print('SyntaxError: EmptyLabel')
            except dns.resolver.NXDOMAIN:
                #save_mxdomain_in_cache(mxdomain)
                publisher.debug('The query name does not exist.')
                print('The query name does not exist.')
            except dns.name.LabelTooLong:
                publisher.debug('The Label is too long')
                print('The Label is too long')
            except dns.exception.Timeout:
                print('dns timeout')
                #save_mxdomain_in_cache(mxdomain)
            except Exception as e:
                print(e)
    return valid_mxdomain 
Example #26
Source File: lib_refine.py    From AIL-framework with GNU Affero General Public License v3.0 4 votes vote down vote up
def checking_A_record(r_serv, domains_set):

    score = 0
    num = len(domains_set)
    WalidA = set([])
    resolver = dns.resolver.Resolver()
    resolver.nameservers = [dns_server]
    resolver.timeout = 5.0
    resolver.lifetime = 2.0

    for Adomain in domains_set:
        try:
            # Already in Redis living.
            if r_serv.exists(Adomain):
                score += 1
                WalidA.add(Adomain)
            # Not already in Redis
            else:
                # If I'm Walid domain
                if resolver.query(Adomain, rdtype=dns.rdatatype.A):
                    # Gonna be added in redis.
                    r_serv.setex(Adomain, 1, timedelta(days=1))
                    score += 1
                    WalidA.add(Adomain)
                else:
                    pass

        except dns.resolver.NoNameservers:
            publisher.debug('NoNameserver, No non-broken nameservers are available to answer the query.')

        except dns.resolver.NoAnswer:
            publisher.debug('NoAnswer, The response did not contain an answer to the question.')

        except dns.name.EmptyLabel:
            publisher.debug('SyntaxError: EmptyLabel')

        except dns.resolver.NXDOMAIN:
            r_serv.setex(Adomain[1:], 1, timedelta(days=1))
            publisher.debug('The query name does not exist.')

        except dns.name.LabelTooLong:
            publisher.debug('The Label is too long')

        except Exception as e:
            print(e)

    publisher.debug("URLs before: {0} after: {1} (valid)".format(num, score))
    return (num, WalidA) 
Example #27
Source File: checkdmarc.py    From checkdmarc with Apache License 2.0 4 votes vote down vote up
def _query_dns(domain, record_type, nameservers=None, timeout=2.0,
               cache=None):
    """
    Queries DNS

    Args:
        domain (str): The domain or subdomain to query about
        record_type (str): The record type to query for
        nameservers (list): A list of one or more nameservers to use
        (Cloudflare's public DNS resolvers by default)
        timeout (float): Sets the DNS timeout in seconds
        cache (ExpiringDict): Cache storage

    Returns:
        list: A list of answers
    """
    domain = str(domain).lower()
    record_type = record_type.upper()
    cache_key = "{0}_{1}".format(domain, record_type)
    if cache is None:
        cache = DNS_CACHE
    if cache:
        records = cache.get(cache_key, None)
        if records:
            return records

    resolver = dns.resolver.Resolver()
    timeout = float(timeout)
    if nameservers is None:
        nameservers = ["1.1.1.1", "1.0.0.1",
                       "2606:4700:4700::1111", "2606:4700:4700::1001",
                       ]
    resolver.nameservers = nameservers
    resolver.timeout = timeout
    resolver.lifetime = timeout
    if record_type == "TXT":
        resource_records = list(map(
            lambda r: r.strings,
            resolver.query(domain, record_type, lifetime=timeout)))
        _resource_record = [
            resource_record[0][:0].join(resource_record)
            for resource_record in resource_records if resource_record]
        records = [r.decode() for r in _resource_record]
    else:
        records = list(map(
            lambda r: r.to_text().replace('"', '').rstrip("."),
            resolver.query(domain, record_type, lifetime=timeout)))
    if cache:
        cache[cache_key] = records

    return records 
Example #28
Source File: checkdmarc.py    From Scrummage with GNU General Public License v3.0 4 votes vote down vote up
def _query_dns(domain, record_type, nameservers=None, timeout=2.0,
               cache=None):
    """
    Queries DNS

    Args:
        domain (str): The domain or subdomain to query about
        record_type (str): The record type to query for
        nameservers (list): A list of one or more nameservers to use
        (Cloudflare's public DNS resolvers by default)
        timeout (float): Sets the DNS timeout in seconds
        cache (ExpiringDict): Cache storage

    Returns:
        list: A list of answers
    """
    domain = str(domain).lower()
    record_type = record_type.upper()
    cache_key = "{0}_{1}".format(domain, record_type)
    if cache is None:
        cache = DNS_CACHE
    if cache:
        records = cache.get(cache_key, None)
        if records:
            return records

    resolver = dns.resolver.Resolver()
    timeout = float(timeout)
    if nameservers is None:
        nameservers = ["1.1.1.1", "1.0.0.1",
                       "2606:4700:4700::1111", "2606:4700:4700::1001",
                       ]
    resolver.nameservers = nameservers
    resolver.timeout = timeout
    resolver.lifetime = timeout
    if record_type == "TXT":
        resource_records = list(map(
            lambda r: r.strings,
            resolver.query(domain, record_type, lifetime=timeout)))
        _resource_record = [
            resource_record[0][:0].join(resource_record)
            for resource_record in resource_records if resource_record]
        records = [r.decode() for r in _resource_record]
    else:
        records = list(map(
            lambda r: r.to_text().replace('"', '').rstrip("."),
            resolver.query(domain, record_type, lifetime=timeout)))
    if cache:
        cache[cache_key] = records

    return records 
Example #29
Source File: utils.py    From parsedmarc with Apache License 2.0 4 votes vote down vote up
def query_dns(domain, record_type, cache=None, nameservers=None, timeout=2.0):
    """
    Queries DNS

    Args:
        domain (str): The domain or subdomain to query about
        record_type (str): The record type to query for
        cache (ExpiringDict): Cache storage
        nameservers (list): A list of one or more nameservers to use
        (Cloudflare's public DNS resolvers by default)
        timeout (float): Sets the DNS timeout in seconds

    Returns:
        list: A list of answers
    """
    domain = str(domain).lower()
    record_type = record_type.upper()
    cache_key = "{0}_{1}".format(domain, record_type)
    if cache:
        records = cache.get(cache_key, None)
        if records:
            return records

    resolver = dns.resolver.Resolver()
    timeout = float(timeout)
    if nameservers is None:
        nameservers = ["1.1.1.1", "1.0.0.1",
                       "2606:4700:4700::1111", "2606:4700:4700::1001",
                       ]
    resolver.nameservers = nameservers
    resolver.timeout = timeout
    resolver.lifetime = timeout
    if record_type == "TXT":
        resource_records = list(map(
            lambda r: r.strings,
            resolver.query(domain, record_type, lifetime=timeout)))
        _resource_record = [
            resource_record[0][:0].join(resource_record)
            for resource_record in resource_records if resource_record]
        records = [r.decode() for r in _resource_record]
    else:
        records = list(map(
            lambda r: r.to_text().replace('"', '').rstrip("."),
            resolver.query(domain, record_type, lifetime=timeout)))
    if cache:
        cache[cache_key] = records

    return records