Python dns.resolver.timeout() Examples

The following are 30 code examples of dns.resolver.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.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.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 #3
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 #4
Source File: email_hacker-GUI.py    From email_hack with MIT License 6 votes vote down vote up
def __init__(self, to_addr, from_addr, SMTP_addr, port=25, timeout=10):
        Print(u"check config", sign=u"[+]")
        Print(u"to address: "+to_addr)
        Print(u"from address: "+from_addr)
        Print(u"SMTP address: "+SMTP_addr)
        Print(u"SMTP port: "+str(port))
        Print(u"socket timeout: "+str(timeout))
        Print(u"verbose level: "+str(verbose))
        Print(u"no problem, maybe", sign=u"  [*]")

        self.to_addr = to_addr
        self.from_addr = from_addr
        self.port = port
        self.timeout = timeout
        self.SMTP_addr = SMTP_addr
        self.quit_flag = 1
        self.succ_num = 0 
Example #5
Source File: util.py    From exchangelib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _may_retry_on_error(response, retry_policy, wait):
    if response.status_code not in (301, 302, 401, 503):
        # Don't retry if we didn't get a status code that we can hope to recover from
        log.debug('No retry: wrong status code %s', response.status_code)
        return False
    if retry_policy.fail_fast:
        log.debug('No retry: no fail-fast policy')
        return False
    if wait > retry_policy.max_wait:
        # We lost patience. Session is cleaned up in outer loop
        raise RateLimitError(
            'Max timeout reached', url=response.url, status_code=response.status_code, total_wait=wait)
    # The genericerrorpage.htm/internalerror.asp is ridiculous behaviour for random outages. Redirect to
    # '/internalsite/internalerror.asp' or '/internalsite/initparams.aspx' is caused by e.g. TLS certificate
    # f*ckups on the Exchange server.
    if (response.status_code == 401) \
            or (response.headers.get('connection') == 'close') \
            or (response.status_code == 302 and response.headers.get('location', '').lower() ==
                '/ews/genericerrorpage.htm?aspxerrorpath=/ews/exchange.asmx') \
            or (response.status_code == 503):
        log.debug('Retry allowed: conditions met')
        return True
    return False 
Example #6
Source File: Unstable_version.py    From email_hack with MIT License 6 votes vote down vote up
def __init__(self, to_addr, from_addr, SMTP_addr, port=25, timeout=10):
        Print(u"check config", sign=u"[+]")
        Print(u"to address: "+to_addr)
        Print(u"from address: "+from_addr)
        Print(u"SMTP address: "+SMTP_addr)
        Print(u"SMTP port: "+str(port))
        Print(u"socket timeout: "+str(timeout))
        Print(u"verbose level: "+str(verbose))
        Print(u"no problem, maybe", sign=u"  [*]")

        self.to_addr = to_addr
        self.from_addr = from_addr
        self.port = port
        self.timeout = timeout
        self.SMTP_addr = SMTP_addr
        self.quit_flag = 1
        self.succ_num = 0
        self.failed_num = 0
        self.msg = PutColor("Connecting...", "yellow") 
Example #7
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 #8
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 #9
Source File: subbrute.py    From ITWSV with MIT License 6 votes vote down vote up
def run(self):
        #Every user will get a different set of resovlers, this helps redistribute traffic.
        random.shuffle(self.resolver_list)
        if not self.verify(self.resolver_list):
            #This should never happen,  inform the user.
            sys.stderr.write('Warning: No nameservers found, trying fallback list.\n')
            #Try and fix it for the user:
            self.verify(self.backup_resolver)
        #End of the resolvers list.
        try:
            self.resolver_q.put(False, timeout = 1)
        except:
            pass

    #Only add the nameserver to the queue if we can detect wildcards. 
    #Returns False on error. 
Example #10
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 #11
Source File: utils.py    From parsedmarc with Apache License 2.0 6 votes vote down vote up
def get_reverse_dns(ip_address, cache=None, nameservers=None, timeout=2.0):
    """
    Resolves an IP address to a hostname using a reverse DNS query

    Args:
        ip_address (str): The IP address to resolve
        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 query timeout in seconds

    Returns:
        str: The reverse DNS hostname (if any)
    """
    hostname = None
    try:
        address = dns.reversename.from_address(ip_address)
        hostname = query_dns(address, "PTR", cache=cache,
                             nameservers=nameservers,
                             timeout=timeout)[0]

    except dns.exception.DNSException:
        pass

    return hostname 
Example #12
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 #13
Source File: email_hacker.py    From email_hack with MIT License 6 votes vote down vote up
def __init__(self, to_addr, from_addr, SMTP_addr, port=25, timeout=10):
        Print(u"check config", sign=u"[+]")
        Print(u"to address: "+to_addr)
        Print(u"from address: "+from_addr)
        Print(u"SMTP address: "+SMTP_addr)
        Print(u"SMTP port: "+str(port))
        Print(u"socket timeout: "+str(timeout))
        Print(u"verbose level: "+str(verbose))
        Print(u"no problem, maybe", sign=u"  [*]")

        self.to_addr = to_addr
        self.from_addr = from_addr
        self.port = port
        self.timeout = timeout
        self.SMTP_addr = SMTP_addr
        self.quit_flag = 1
        self.succ_num = 0 
Example #14
Source File: dnsutils.py    From maltelligence with GNU General Public License v3.0 6 votes vote down vote up
def retIP(domain, ns=None):
    #   added the ns option to handle CDN case where cn format = "x.x.x.x",
    #   consider using public name servers provided http://public-dns.tk or use nameservers.keys()
    ip = ''
    c_name = ''
    if domain == '':
        return ip, c_name
    resolver = dns.resolver.Resolver()
    resolver.timeout = 1
    try:
        answers = resolver.query(domain)
        ip = str(answers[0]).split(": ")[0]
        c_name = answers.canonical_name
    except Exception, e:
        msg = '[*] No IP Addressed: Timeout, NXDOMAIN, NoAnswer or NoNameservers'
        logging.info(msg) 
Example #15
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 #16
Source File: subbrute.py    From Yuki-Chan-The-Auto-Pentest with MIT License 6 votes vote down vote up
def run(self):
        #Every user will get a different set of resovlers, this helps redistribute traffic.
        random.shuffle(self.resolver_list)
        if not self.verify(self.resolver_list):
            #This should never happen,  inform the user.
            sys.stderr.write('Warning: No nameservers found, trying fallback list.\n')
            #Try and fix it for the user:
            self.verify(self.backup_resolver)
        #End of the resolvers list.
        try:
            self.resolver_q.put(False, timeout = 1)
        except:
            pass

    #Only add the nameserver to the queue if we can detect wildcards. 
    #Returns False on error. 
Example #17
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 #18
Source File: subbrute.py    From subtake with GNU General Public License v2.0 6 votes vote down vote up
def run(self):
        #Every user will get a different set of resovlers, this helps redistribute traffic.
        random.shuffle(self.resolver_list)
        if not self.verify(self.resolver_list):
            #This should never happen,  inform the user.
            sys.stderr.write('Warning: No nameservers found, trying fallback list.\n')
            #Try and fix it for the user:
            self.verify(self.backup_resolver)
        #End of the resolvers list.
        try:
            self.resolver_q.put(False, timeout = 1)
        except:
            pass

    #Only add the nameserver to the queue if we can detect wildcards. 
    #Returns False on error. 
Example #19
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 #20
Source File: checkdmarc.py    From checkdmarc with Apache License 2.0 5 votes vote down vote up
def test_dnssec(domain, nameservers=None, timeout=2.0):
    """
    Check for DNSSEC on the given domain

    Args:
        domain (str): The domain to check
        nameservers (list): A list of nameservers to query
        timeout (float): Timeout in seconds

    Returns:
        bool: DNSSEC status
    """
    if nameservers is None:
        nameservers = ["1.1.1.1", "1.0.0.1",
                       "2606:4700:4700::1111", "2606:4700:4700::1001",
                       ]
    request = dns.message.make_query(get_base_domain(domain),
                                     dns.rdatatype.NS,
                                     want_dnssec=True)
    for nameserver in nameservers:
        try:
            response = dns.query.udp(request, nameserver, timeout=timeout)
            if response is not None:
                for record in response.answer:
                    if record.rdtype == dns.rdatatype.RRSIG:
                        if response.flags & dns.flags.AD:
                            return True
        except Exception as e:
            logging.debug("DNSSEC query error: {0}".format(e))

    return False 
Example #21
Source File: dnsutils.py    From maltelligence with GNU General Public License v3.0 5 votes vote down vote up
def chk_connected():
    try:
        response=urllib2.urlopen('http://www.google.com',timeout=1)
        return True
    except urllib2.URLError as err:
        pass
    return False 
Example #22
Source File: checkdmarc.py    From checkdmarc with Apache License 2.0 5 votes vote down vote up
def __init__(self, error):
        if isinstance(error, dns.exception.Timeout):
            error.kwargs["timeout"] = round(error.kwargs["timeout"], 1) 
Example #23
Source File: util.py    From exchangelib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def is_valid_hostname(hostname, timeout):
    log.debug('Checking if %s can be looked up in DNS', hostname)
    resolver = dns.resolver.Resolver()
    resolver.timeout = timeout
    try:
        resolver.query(hostname)
    except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
        return False
    return True 
Example #24
Source File: discovery.py    From exchangelib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _get_srv_records(hostname):
    """Send a DNS query for SRV entries for the hostname.

    An SRV entry that has been formatted for autodiscovery will have the following format:

        canonical name = mail.example.com.
        service = 8 100 443 webmail.example.com.

    The first three numbers in the service line are: priority, weight, port

    Args:
      hostname:

    """
    log.debug('Attempting to get SRV records for %s', hostname)
    resolver = dns.resolver.Resolver()
    resolver.timeout = AutodiscoverProtocol.TIMEOUT
    records = []
    try:
        answers = resolver.query('%s.' % hostname, 'SRV')
    except (dns.resolver.NoNameservers, dns.resolver.NoAnswer, dns.resolver.NXDOMAIN) as e:
        log.debug('DNS lookup failure: %s', e)
        return records
    for rdata in answers:
        try:
            vals = rdata.to_text().strip().rstrip('.').split(' ')
            # Raise ValueError if the first three are not ints, and IndexError if there are less than 4 values
            priority, weight, port, srv = int(vals[0]), int(vals[1]), int(vals[2]), vals[3]
            record = SrvRecord(priority=priority, weight=weight, port=port, srv=srv)
            log.debug('Found SRV record %s ', record)
            records.append(record)
        except (ValueError, IndexError):
            log.debug('Incompatible SRV record for %s (%s)', hostname, rdata.to_text())
    return records 
Example #25
Source File: checkdmarc.py    From Scrummage with GNU General Public License v3.0 5 votes vote down vote up
def test_dnssec(domain, nameservers=None, timeout=2.0):
    """
    Check for DNSSEC on the given domain

    Args:
        domain (str): The domain to check
        nameservers (list): A list of nameservers to query
        timeout (float): Timeout in seconds

    Returns:
        bool: DNSSEC status
    """
    if nameservers is None:
        nameservers = ["1.1.1.1", "1.0.0.1",
                       "2606:4700:4700::1111", "2606:4700:4700::1001",
                       ]
    request = dns.message.make_query(get_base_domain(domain),
                                     dns.rdatatype.NS,
                                     want_dnssec=True)
    for nameserver in nameservers:
        try:
            response = dns.query.udp(request, nameserver)
            if response is not None:
                for record in response.answer:
                    if record.rdtype == dns.rdatatype.RRSIG:
                        if response.flags & dns.flags.AD:
                            return True
        except Exception as e:
            logging.debug("DNSSEC query error: {0}".format(e))

    return False 
Example #26
Source File: checkdmarc.py    From Scrummage with GNU General Public License v3.0 5 votes vote down vote up
def get_nameservers(domain, approved_nameservers=None,
                    nameservers=None, timeout=2.0):
    """
    Gets a list of nameservers for a given domain

    Args:
        domain (str): A domain name
        approved_nameservers (list): A list of approved nameserver substrings
        nameservers (list): A list of nameservers to qu+ery
        (Cloudflare's by default)
        timeout(float): number of seconds to wait for an record from DNS

    Returns:
        Dict: A dictionary with the following keys:
              - ``hostnames`` - A list of nameserver hostnames
              - ``warnings``  - A list of warnings
    """
    logging.debug("Getting NS records on {0}".format(domain))
    warnings = []

    ns_records = _get_nameservers(domain, nameservers=nameservers)

    if approved_nameservers:
        approved_nameservers = list(map(lambda h: h.lower(),
                                        approved_nameservers))
    for nameserver in ns_records:
        if approved_nameservers:
            approved = False
            for approved_nameserver in approved_nameservers:
                if approved_nameserver in nameserver.lower():
                    approved = True
                    break
            if not approved:
                warnings.append("Unapproved nameserver: {0}".format(
                    nameserver
                ))

    return OrderedDict([("hostnames", ns_records), ("warnings", warnings)]) 
Example #27
Source File: checkdmarc.py    From Scrummage with GNU General Public License v3.0 5 votes vote down vote up
def get_spf_record(domain, nameservers=None, timeout=2.0):
    """
    Retrieves and parses an SPF record

    Args:
        domain (str): A domain name
        nameservers (list): A list of nameservers to query
        (Cloudflare's by default)
        timeout(float): Number of seconds to wait for an answer from DNS

    Returns:
        OrderedDict: An SPF record parsed by result

    Raises:
        :exc:`checkdmarc.SPFRecordNotFound`
        :exc:`checkdmarc.SPFIncludeLoop`
        :exc:`checkdmarc.SPFRedirectLoop`
        :exc:`checkdmarc.SPFSyntaxError`
        :exc:`checkdmarc.SPFTooManyDNSLookups`

    """
    record = query_spf_record(domain, nameservers=nameservers)
    record = record["record"]
    parsed_record = parse_spf_record(record, domain, nameservers=nameservers)
    parsed_record["record"] = record

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

    Args:
        domain (str): A domain name
        nameservers (list): A list of nameservers to query
        (Cloudflare's by default)
        timeout(float): number of seconds to wait for an answer from DNS

    Returns:
        list: A list of TXT records

     Raises:
        :exc:`checkdmarc.DNSException`

    """
    try:
        records = _query_dns(domain, "TXT", nameservers=nameservers)
    except dns.resolver.NXDOMAIN:
        raise DNSException("The domain {0} does not exist".format(domain))
    except dns.resolver.NoAnswer:
        raise DNSException(
            "The domain {0} does not have any TXT records".format(domain))
    except Exception as error:
        raise DNSException(error)

    return records 
Example #29
Source File: checkdmarc.py    From Scrummage with GNU General Public License v3.0 5 votes vote down vote up
def _get_a_records(domain, nameservers=None, timeout=2.0):
    """
    Queries DNS for A and AAAA records

    Args:
        domain (str): A domain name
        nameservers (list): A list of nameservers to query
        (Cloudflare's by default)
        timeout(float): number of seconds to wait for an answer from DNS

    Returns:
        list: A sorted list of IPv4 and IPv6 addresses

    Raises:
        :exc:`checkdmarc.DNSException`

    """
    qtypes = ["A", "AAAA"]
    addresses = []
    for qt in qtypes:
        try:
            addresses += _query_dns(domain, qt, nameservers=nameservers)
        except dns.resolver.NXDOMAIN:
            raise DNSException("The domain {0} does not exist".format(domain))
        except dns.resolver.NoAnswer:
            # Sometimes a domain will only have A or AAAA records, but not both
            pass
        except Exception as error:
            raise DNSException(error)

    addresses = sorted(addresses)
    return addresses 
Example #30
Source File: checkdmarc.py    From Scrummage with GNU General Public License v3.0 5 votes vote down vote up
def _get_mx_hosts(domain, nameservers=None, timeout=2.0):
    """
    Queries DNS for a list of Mail Exchange hosts

    Args:
        domain (str): A domain name
        nameservers (list): A list of nameservers to query
        (Cloudflare's by default)

    Returns:
        list: A list of ``OrderedDicts``; each containing a ``preference``
                        integer and a ``hostname``

    Raises:
        :exc:`checkdmarc.DNSException`

    """
    hosts = []
    try:
        logging.debug("Checking for MX records on {0}".format(domain))
        answers = _query_dns(domain, "MX", nameservers=nameservers)
        for record in answers:
            record = record.split(" ")
            preference = int(record[0])
            hostname = record[1].rstrip(".").strip().lower()
            hosts.append(OrderedDict(
                [("preference", preference), ("hostname", hostname)]))
        hosts = sorted(hosts, key=lambda h: (h["preference"], h["hostname"]))
    except dns.resolver.NXDOMAIN:
        raise DNSException("The domain {0} does not exist".format(domain))
    except dns.resolver.NoAnswer:
        pass
    except Exception as error:
        raise DNSException(error)
    return hosts