Пример #1
0
def check_txt(domain, status):
    spf, dmarc = 1, 1
    if u"Не делегирован" in status:
        return spf, dmarc
    try:
        mess = dns.resolver.query(
            dns_name.from_text(domain),
            dns.rdatatype.TXT)
    except Exception:
        spf = 1
    else:
        txts = [rdata.to_text() for rdata in mess]
        spfs = filter(lambda i: "v=spf1" in i, txts)
        if not spfs:
            spf = 1
        else:
            if "+all" in " ".join(spfs):
                spf = 2
            else:
                spf = 0
    try:
        mess = dns.resolver.query(
            dns_name.from_text("_dmarc." + domain),
            dns.rdatatype.TXT)
    except:
        return spf, dmarc
    else:
        txts = [txt for rdata in mess for txt in rdata.strings]

        dmarc = 0 if filter(lambda i: "v=DMARC1" in i, txts) else 1
        return spf, dmarc
Пример #2
0
 def fetch_dns(self):
     try:
         name_server = self.settings.get("dns", "server")
         keyring = dns.tsigkeyring.from_text(
                 {self.settings.get("dns", "tsig_name"):
                  self.settings.get("dns", "tsig_key")}
         )
         for domain in self.settings.get("dns", "domains").split(","):
             try:
                 responses = query.xfr(
                         name_server,
                         dns_name.from_text(domain),
                         keyring=keyring,
                         keyname=self.settings.get("dns", "tsig_name"),
                         keyalgorithm=dns.tsig.HMAC_SHA512
                 )
                 with open(pjoin(self.configs, "dns." + domain),
                           "w") as config:
                     for response in responses:
                         for line in response.answer:
                             config.write(line.to_text() + u"\n")
             except:
                 pass
     except:
         logging.error("can't fetch from DNS: %s" %
                       self.settings.get('dns', 'server'))
Пример #3
0
def do_reverse_check(lookup, fip, host):
    """Do PTR record checks"""
    hostfromdns = name.from_text(fip)
    if str(hostfromdns) == str(fip):
        print " [OK] "
    else:
        print " [ERROR!!  DNS:" + str(hostfromdns) + "  FILE: " + fip + "] "
Пример #4
0
    def test(self, req, author, content, ip):
        if self.karma_points == 0:
            return

        serverlist, prefix = self._getdata(ip)
        if not serverlist:
            self.log.warning("No IP blacklist servers configured")
            return

        self.log.debug('Checking for IP blacklisting on "%s"', ip)

        points = 0
        servers = []

        for server in serverlist:
            self.log.debug("Checking blacklist %s for %s [%s]", server, ip,
                           prefix)
            try:
                res = query(from_text(prefix +
                                      server.encode('utf-8')))[0].to_text()
                points -= abs(self.karma_points)
                if res == '127.0.0.1':
                    servers.append(server)
                else:
                    # strip the common part of responses
                    if res.startswith('127.0.0.'):
                        res = res[8:]
                    elif res.startswith('127.'):
                        res = res[4:]
                    servers.append('%s [%s]' % (server, res))
            except NXDOMAIN:  # not blacklisted on this server
                continue
            except (Timeout, NoAnswer, NoNameservers), e:
                self.log.warning('Error checking IP blacklist server "%s" '
                                 'for IP "%s": %s', server, ip, e)
Пример #5
0
 def _query(self, url, server):
     res = query(from_text(url + '.' + server.encode('utf-8')))[0].to_text()
     if res == '127.0.0.1':
         return '%s (%s)' % (server, url)
     # strip the common part of responses
     if res.startswith('127.0.0.'):
         res = res[8:]
     elif res.startswith('127.'):
         res = res[4:]
     return '%s (%s[%s])' % (server, url, res)
Пример #6
0
 def test_should_return_a_list_of_records(self):
     with mock.patch('dns.resolver.query') as query:
         query_name = name.from_text('foo.bar.baz.')
         msg = message.from_text(self.MESSAGE)
         answer = resolver.Answer(query_name,
                                  33, 1, msg,
                                  msg.answer[0])
         query.return_value = answer
         self.assertEqual(srvlookup.lookup('foo', 'bar', 'baz'),
                          [srvlookup.SRV('1.2.3.5', 11211, 1, 0),
                           srvlookup.SRV('1.2.3.4', 11211, 2, 0)])
Пример #7
0
    def addSOA(self, mname, rname, serial, refresh, retry, expire, minimum):
        """
        Adds a start of authority record to the zone.

        :param mname:
        :param rname:
        :param serial:
        :param refresh:
        :param retry:
        :param expire:
        :param minimum:

        """
        import dns.rdtypes.ANY.SOA as rdtype

        rdataset = self.nix_zone.find_rdataset('@', rdtype=rdatatype.SOA, create=True)
        rdata = rdtype.SOA(rdataclass.IN, rdatatype.SOA, name.from_text(mname), name.from_text(rname), int(serial),
                                        int(refresh), int(retry), int(expire), int(minimum))
        rdataset.add(rdata, ttl=self.ttl)
        return
Пример #8
0
    def __init__(self, zone_name):
        if isinstance(zone_name, str):
            self.nix_zone = zone.Zone(name.from_text(zone_name))
            self.domain = self.nix_zone.origin

        elif isinstance(zone_name, zone.Zone):
            self.nix_zone = zone_name
            self.domain = zone_name.origin

        else:
            raise ZoneInvalid('Invalid zone.  Must be dnspython Zone object or domain name as string.')
        return
Пример #9
0
 def test_should_return_name_when_addt_record_is_missing(self):
     with mock.patch('dns.resolver.query') as query:
         query_name = name.from_text('foo.bar.baz.')
         msg = self.get_message(additional_answers=[
             'foo.bar.baz. 0 IN SRV 3 0 11213 foo3.bar.baz.'])
         answer = resolver.Answer(query_name,
                                  33, 1, msg,
                                  msg.answer[0])
         query.return_value = answer
         self.assertEqual(srvlookup.lookup('foo', 'bar', 'baz'),
                          [srvlookup.SRV('1.2.3.5', 11212, 1, 0),
                           srvlookup.SRV('1.2.3.4', 11211, 2, 0),
                           srvlookup.SRV('foo3.bar.baz', 11213, 3, 0)])
Пример #10
0
 def check_dns(domain, ns):
     ns_s = filter(len, map(lambda s: s.strip(),
                            ns.replace('"', '').split(';')))
     if len(ns_s) < 1:
         return {}
     mess = dns.message.make_query(dns_name.from_text(domain),
                                   dns.rdatatype.SOA)
     result = {}
     for ns in ns_s:
         try:
             name_s = dns_name.from_text(ns.split()[0]).to_text()
             answer = query.tcp(mess, name_s, timeout=2)
             if len(answer.authority):
                 result[ns] = True
             else:
                 rr = answer.answer[0][0]
                 if rr.rdtype == dns.rdatatype.SOA:
                     result[ns] = True
                 else:
                     result[ns] = False
         except:
             result[ns] = False
     return result
Пример #11
0
    def test_should_include_local_domain_when_omitted(self):

        with mock.patch('dns.resolver.query') as query:
            with mock.patch('socket.getfqdn') as getfqdn:
                getfqdn.return_value = 'baz'
                query_name = name.from_text('foo.bar.baz.')
                msg = message.from_text(self.MESSAGE)
                answer = resolver.Answer(query_name,
                                         33, 1, msg,
                                         msg.answer[0])
                query.return_value = answer
                self.assertEqual(srvlookup.lookup('foo', 'bar'),
                                 [srvlookup.SRV('1.2.3.5', 11211, 1, 0),
                                  srvlookup.SRV('1.2.3.4', 11211, 2, 0)])
Пример #12
0
    def addCNAME(self, record_name, target):
        """
        Adds a CNAME record to the zone.

        :param record_name: String which represents the DNS name for the record.
        :param target: Target of DNS name.

        """
        import dns.rdtypes.ANY.CNAME as rdtype

        rdataset = self.nix_zone.find_rdataset(record_name, rdtype=rdatatype.CNAME, create=True)
        rdata = rdtype.CNAME(rdataclass.IN, rdatatype.CNAME, name.from_text(target))
        rdataset.add(rdata, ttl=self.ttl)
        return
Пример #13
0
    def addNS(self, record_name, host):
        """
        Adds a NS record to the zone.

        :param record_name: String which represents the DNS name for the record.
        :param host: Hostname of the nameserver being added.

        """
        import dns.rdtypes.ANY.NS as rdtype

        rdataset = self.nix_zone.find_rdataset(record_name, rdtype=rdatatype.NS, create=True)
        rdata = rdtype.NS(rdataclass.IN, rdatatype.NS, name.from_text(host))
        rdataset.add(rdata, ttl=self.ttl)
        
        return
Пример #14
0
    def addMX(self, record_name, exchanger, priority):
        """
        Adds a MX record to the zone.

        :param record_name: String which represents the DNS name for the record.
        :param exchanger: Host to point this MX record at.
        :param priority: MX record priority.

        """
        import dns.rdtypes.ANY.MX as rdtype
        
        rdataset = self.nix_zone.find_rdataset(record_name, rdtype=rdatatype.MX, create=True)
        rdata = rdtype.MX(rdataclass.IN, rdatatype.MX, priority, name.from_text(exchanger))
        rdataset.add(rdata, ttl=self.ttl)
        return
Пример #15
0
    def addSRV(self, record_name, priority, weight, port, target):
        """
        Adds a SRV record to the zone.

        :param record_name:
        :param priority:
        :param weight:
        :param port:
        :param target:
        
        """
        import dns.rdtypes.IN.SRV as rdtype
        
        rdataset = self.nix_zone.find_rdataset(record_name, rdtype=rdatatype.SRV, create=True)
        rdata = rdtype.SRV(rdataclass.IN, rdatatype.SRV, priority, weight, port, name.from_text(target))
        rdataset.add(rdata, ttl=self.ttl)
        return
Пример #16
0
def WriteToZoneFile(zone_file, record_sets, domain):
  """Writes the given record-sets in zone file format to the given file.

  Args:
    zone_file: file, File into which the records should be written.
    record_sets: list, ResourceRecordSets to be written out.
    domain: str, The origin domain for the zone file.
  """
  zone_contents = zone.Zone(name.from_text(domain))
  for record_set in record_sets:
    rdset = zone_contents.get_rdataset(record_set.name,
                                       record_set.type,
                                       create=True)
    for rrdata in record_set.rrdatas:
      rdset.add(rdata.from_text(rdataclass.IN,
                                rdatatype.from_text(record_set.type),
                                str(rrdata),
                                origin=zone_contents.origin),
                ttl=record_set.ttl)
  zone_contents.to_file(zone_file, relativize=False)
Пример #17
0
 def test_create_simple_rrset(self):
     rrset = create_simple_rrset("localhost", "127.0.0.1")
     assert rrset
     assert rrset.name == from_text("localhost.")
Пример #18
0
    def _test_hit_authority(self, nameserver, aggressive=False):
        name = "a.gtld-servers.net."

        resolver = self.get_test_resolver(nameserver)

        try:
            q1 = resolver.query(name, A)
        except Timeout:
            raise unittest.SkipTest("Timeout occurred")

        if not q1.response.authority:
            raise unittest.SkipTest("no authority section")

        if aggressive:
            assert len(resolver.cache.data) >= 1
        else:
            assert len(resolver.cache.data) == 1

        name = from_text(name)
        assert (name, A, IN) in resolver.cache.data
        assert resolver.cache.get((name, A, IN))

        entry = resolver.cache.data[(name, A, IN)]

        if isinstance(entry, LRUCacheNode):
            answer = entry.value
        else:
            answer = entry

        assert answer == q1

        rrsets = answer.response.answer
        assert rrsets
        assert len(rrsets) == 1

        names = set([rrset.name for rrset in rrsets])

        assert len(names) == 1

        assert len(answer.response.authority) == 1

        rrsets = answer.response.authority

        assert rrsets
        assert len(rrsets) == 1

        authority_names = sorted(set([
            rrset.name for rrset in rrsets
            if rrset.rdtype == NS and rrset.rdclass == IN
        ]))

        with dnspython_resolver_socket_block():
            q2 = resolver.query(name, A)

        if aggressive:
            assert len(resolver.cache.data) >= 1
        else:
            assert len(resolver.cache.data) == 1

        assert q2 is q1

        if aggressive:
            return resolver, authority_names

        with self.assertRaises(_SocketBlockedError):
            with dnspython_resolver_socket_block():
                resolver.query(authority_names[0], NS)
Пример #19
0
def check_dns_resolution(host_name, dns_servers):
    """Check forward and reverse resolution of host_name using dns_servers
    """
    # Point the resolver at specified DNS server
    server_ips = []
    for dns_server in dns_servers:
        try:
            server_ips = list(
                a[4][0] for a in socket.getaddrinfo(dns_server, None))
        except socket.error:
            pass
        else:
            break
    if not server_ips:
        root_logger.error(
            'Could not resolve any DNS server hostname: %s', dns_servers)
        return False
    resolver = dnsresolver.Resolver()
    resolver.nameservers = server_ips

    root_logger.debug('Search DNS server %s (%s) for %s',
                      dns_server, server_ips, host_name)

    # Get IP addresses of host_name
    addresses = set()
    for rtype in 'A', 'AAAA':
        try:
            result = resolver.query(host_name, rtype)
        except dnsexception.DNSException:
            rrset = []
        else:
            rrset = result.rrset
        if rrset:
            addresses.update(r.address for r in result.rrset)

    if not addresses:
        root_logger.error(
            'Could not resolve hostname %s using DNS. '
            'Clients may not function properly. '
            'Please check your DNS setup. '
            '(Note that this check queries IPA DNS directly and '
            'ignores /etc/hosts.)',
            host_name)
        return False

    no_errors = True

    # Check each of the IP addresses
    checked = set()
    for address in addresses:
        if address in checked:
            continue
        checked.add(address)
        try:
            root_logger.debug('Check reverse address %s (%s)',
                              address, host_name)
            revname = dnsreversename.from_address(address)
            rrset = resolver.query(revname, 'PTR').rrset
        except Exception, e:
            root_logger.debug('Check failed: %s %s', type(e).__name__, e)
            root_logger.error(
                'Reverse DNS resolution of address %s (%s) failed. '
                'Clients may not function properly. '
                'Please check your DNS setup. '
                '(Note that this check queries IPA DNS directly and '
                'ignores /etc/hosts.)',
                address, host_name)
            no_errors = False
        else:
            host_name_obj = dnsname.from_text(host_name)
            if rrset:
                names = [r.target.to_text() for r in rrset]
            else:
                names = []
            root_logger.debug(
                'Address %s resolves to: %s. ', address, ', '.join(names))
            if not rrset or not any(
                    r.target == host_name_obj for r in rrset):
                root_logger.error(
                    'The IP address %s of host %s resolves to: %s. '
                    'Clients may not function properly. '
                    'Please check your DNS setup. '
                    '(Note that this check queries IPA DNS directly and '
                    'ignores /etc/hosts.)',
                    address, host_name, ', '.join(names))
                no_errors = False
Пример #20
0
 def test_decode(self):
     assert key_decode("foo.bar.!1!1") == (from_text("foo.bar."), A, IN)
     assert key_decode("foo!bar.!1!1") == (from_text("foo!bar."), A, IN)
Пример #21
0
    def test_nxdomain(self, expected_extra=0, long_expiry=False, ignore_any=False):
        missing_name = "invalid.invalid."

        expected_cache_count = expected_extra + (1 if DNSPYTHON_2 else 0)

        resolver = self.get_test_resolver()

        if DNSPYTHON_2:
            query = resolver.resolve
        else:
            query = resolver.query

        try:
            query(missing_name)
        except NXDOMAIN:
            pass
        else:
            raise unittest.SkipTest("DNS hijacked")

        e_qnames = e_responses = None
        with self.assertRaises(NXDOMAIN) as first_e:
            query(missing_name)

        if not hasattr(first_e, "qnames"):
            first_e = first_e.exception
        e_qnames, e_responses = _get_nxdomain_exception_values(first_e)
        assert e_qnames and e_responses

        name = from_text(missing_name)
        assert e_qnames == [name]

        assert len(resolver.cache.data) == expected_cache_count

        self._flush_cache(resolver)

        with self.assertRaises(NXDOMAIN):
            query(missing_name, A, tcp=True)

        assert len(resolver.cache.data) == expected_cache_count

        if DNSPYTHON_2:
            assert (name, ANY, IN) in resolver.cache.data
            entry = resolver.cache.data[(name, ANY, IN)]
            assert entry is not None

            if isinstance(entry, LRUCacheNode):
                entry = entry.value

            assert isinstance(entry, Answer)

        if expected_extra:
            assert (name, A, IN) in resolver.cache.data
        else:
            assert (name, A, IN) not in resolver.cache.data

        # While dnspython 2 creates a cache entry for ANY,
        # requests for ANY fail, and the cache entry persists
        with self.assertRaises(NoMetaqueries):
            query(missing_name, ANY)

        # The exception caching .resolve sets ignore_any becase it
        # fetches from the cache, which removes the cache entry unless
        # the expiration is high
        if DNSPYTHON_2 and not ignore_any:
            assert (name, ANY, IN) in resolver.cache.data
            entry = resolver.cache.data[(name, ANY, IN)]
            assert entry is not None

            if isinstance(entry, LRUCacheNode):
                entry = entry.value

            assert isinstance(entry, Answer)

        with self.assertRaises(NXDOMAIN):
            query(missing_name, A, tcp=True)

        # While dnspython 2 creates a cache entry for ANY, and it uses
        # that caching to response to A without network activity,
        # the cache entry expiries very quickly.  This appear to be
        # improved in dnspython 2.1dev.
        if not long_expiry:
            if DNSPYTHON_2:
                long_expiry = True

        if long_expiry:
            with self.assertRaises(NXDOMAIN):
                with dnspython_resolver_socket_block():
                    query(missing_name, A)

        # bailout because test_exceptions would fail the below assertion, as the
        # exception NODOMAIN will be raised even when the socket is blocked
        if expected_extra or long_expiry:
            return resolver, first_e

        with self.assertRaises(_SocketBlockedError):
            with dnspython_resolver_socket_block():
                query(missing_name, A)
Пример #22
0
class NSEC3Hash(unittest.TestCase):

    DATA = [
        # Source: https://tools.ietf.org/html/rfc5155#appendix-A
        ("example", "aabbccdd", 12, "0p9mhaveqvm6t7vbl5lop2u3t2rp3tom", 1),
        ("a.example", "aabbccdd", 12, "35mthgpgcu1qg68fab165klnsnk3dpvl", 1),
        ("ai.example", "aabbccdd", 12, "gjeqe526plbf1g8mklp59enfd789njgi", 1),
        ("ns1.example", "aabbccdd", 12, "2t7b4g4vsa5smi47k61mv5bv1a22bojr", 1),
        ("ns2.example", "aabbccdd", 12, "q04jkcevqvmu85r014c7dkba38o0ji5r", 1),
        ("w.example", "aabbccdd", 12, "k8udemvp1j2f7eg6jebps17vp3n8i58h", 1),
        ("*.w.example", "aabbccdd", 12, "r53bq7cc2uvmubfu5ocmm6pers9tk9en", 1),
        ("x.w.example", "aabbccdd", 12, "b4um86eghhds6nea196smvmlo4ors995", 1),
        ("y.w.example", "aabbccdd", 12, "ji6neoaepv8b5o6k4ev33abha8ht9fgc", 1),
        ("x.y.w.example", "aabbccdd", 12, "2vptu5timamqttgl4luu9kg21e0aor3s",
         1),
        ("xx.example", "aabbccdd", 12, "t644ebqk9bibcna874givr6joj62mlhv", 1),
        (
            "2t7b4g4vsa5smi47k61mv5bv1a22bojr.example",
            "aabbccdd",
            12,
            "kohar7mbb8dc2ce8a9qvl8hon4k53uhi",
            1,
        ),
        # Source: generated with knsec3hash (Linux knot package)
        ("example.com", "9F1AB450CF71D6", 0,
         "qfo2sv6jaej4cm11a3npoorfrckdao2c", 1),
        ("example.com", "9F1AB450CF71D6", 1,
         "1nr64to0bb861lku97deb4ubbk6cl5qh", 1),
        ("example.com.", "AF6AB45CCF79D6", 6,
         "sale3fn6penahh1lq5oqtr5rcl1d113a", 1),
        ("test.domain.dev.", "", 6, "8q98lv9jgkhoq272e42c8blesivia7bu", 1),
        ("www.test.domain.dev.", "B4", 2, "nv7ti6brgh94ke2f3pgiigjevfgpo5j0",
         1),
        ("*.test-domain.dev", "", 0, "o6uadafckb6hea9qpcgir2gl71vt23gu", 1),
        ("*.test-domain.dev", "", 45, "505k9g118d9sofnjhh54rr8fadgpa0ct", 1),
        # Alternate forms of parameters
        (
            name.from_text("example"),
            "aabbccdd",
            12,
            "0p9mhaveqvm6t7vbl5lop2u3t2rp3tom",
            1,
        ),
        (
            "example",
            b"\xaa\xbb\xcc\xdd",
            12,
            "0p9mhaveqvm6t7vbl5lop2u3t2rp3tom",
            1,
        ),
        ("*.test-domain.dev", None, 45, "505k9g118d9sofnjhh54rr8fadgpa0ct", 1),
        (
            "example",
            "aabbccdd",
            12,
            "0p9mhaveqvm6t7vbl5lop2u3t2rp3tom",
            dnssec.NSEC3Hash.SHA1,
        ),
        ("example", "aabbccdd", 12, "0p9mhaveqvm6t7vbl5lop2u3t2rp3tom",
         "SHA1"),
        ("example", "aabbccdd", 12, "0p9mhaveqvm6t7vbl5lop2u3t2rp3tom",
         "sha1"),
    ]

    def test_hash_function(self):
        for d in self.DATA:
            hash = dnssec.nsec3_hash(d[0], d[1], d[2], d[4])
            self.assertEqual(hash, d[3].upper(), "Error {}".format(d))

    def test_hash_invalid_salt_length(self):
        data = (
            "example.com",
            "9F1AB450CF71D",
            0,
            "qfo2sv6jaej4cm11a3npoorfrckdao2c",
            1,
        )
        with self.assertRaises(ValueError):
            hash = dnssec.nsec3_hash(data[0], data[1], data[2], data[4])

    def test_hash_invalid_algorithm(self):
        data = (
            "example.com",
            "9F1AB450CF71D",
            0,
            "qfo2sv6jaej4cm11a3npoorfrckdao2c",
            1,
        )
        with self.assertRaises(ValueError):
            dnssec.nsec3_hash(data[0], data[1], data[2], 10)
        with self.assertRaises(ValueError):
            dnssec.nsec3_hash(data[0], data[1], data[2], "foo")
Пример #23
0
    def _test_hit_additional(self, nameserver, aggressive=False):
        name = "cloudflare.com."

        resolver = self.get_test_resolver(nameserver)

        try:
            q1 = resolver.query(name, NS)
        except Timeout:
            raise unittest.SkipTest("Timeout occurred")

        if not q1.response.additional:
            raise unittest.SkipTest("no additional section")

        # Many US servers are returning an additional section with
        # only a single entry, as opposed to many as expected by the logic.
        if len(q1.response.additional) == 1:
            raise unittest.SkipTest("additional section has one entry")

        if aggressive:
            assert len(resolver.cache.data) > 1
        else:
            assert len(resolver.cache.data) == 1

        name = from_text(name)
        assert (name, NS, IN) in resolver.cache.data
        assert resolver.cache.get((name, NS, IN))

        entry = resolver.cache.data[(name, NS, IN)]

        if isinstance(entry, LRUCacheNode):
            answer = entry.value
        else:
            answer = entry

        rrsets = answer.response.answer
        assert rrsets
        assert len(rrsets) == 1
        names = set([rrset.name for rrset in rrsets])

        assert len(names) == 1
        rrset = [rrset for rrset in rrsets][0]

        assert len(answer.response.additional) > 1

        rrsets = answer.response.additional
        assert rrsets
        assert len(rrsets) > 1

        additional_names = sorted(set([
            rrset.name for rrset in rrsets
            if rrset.rdclass == IN
        ]))
        assert additional_names

        additional_a_names = sorted(set([
            rrset.name for rrset in rrsets
            if rrset.rdtype == A and rrset.rdclass == IN
        ]))

        if not additional_a_names:
            additional_aaaa_names = sorted(set([
                rrset.name for rrset in rrsets
                if rrset.rdtype == AAAA and rrset.rdclass == IN
            ]))
            if additional_aaaa_names:
                raise unittest.SkipTest("Additional only has AAAA")

        assert additional_a_names

        with dnspython_resolver_socket_block():
            q2 = resolver.query(name, NS)

        if aggressive:
            assert len(resolver.cache.data) > 1
        else:
            assert len(resolver.cache.data) == 1

        assert q2 is q1

        if aggressive:
            return resolver, additional_a_names

        with self.assertRaises(_SocketBlockedError):
            with dnspython_resolver_socket_block():
                ip = resolver.query(additional_a_names[0], A)

        return resolver
Пример #24
0
def replica_krb_init_info(ansible_log,
                          fstore,
                          realm_name,
                          master_host_name,
                          host_name,
                          domain_name,
                          admin_password,
                          no_pkinit,
                          subject_base,
                          pkcs12_info=None):
    # promote is not needed here

    # From replicainstall.install_krb
    krb = krbinstance.KrbInstance(fstore=fstore)
    krb.set_output(ansible_log)

    # pkinit files
    if pkcs12_info is None:
        pkcs12_info = make_pkcs12_info(config.dir, "pkinitcert.p12",
                                       "pkinit_pin.txt")

    #krb.create_replica(realm_name,
    #                   master_host_name, host_name,
    #                   domain_name, dirman_password,
    #                   setup_pkinit, pkcs12_info,
    #                   subject_base=subject_base,
    #                   promote=promote)
    with redirect_stdout(ansible_log):
        krb.init_info(realm_name,
                      host_name,
                      setup_pkinit=not no_pkinit,
                      subject_base=subject_base)

        # From ipaserver.install.krbinstance.create_replica

        krb.pkcs12_info = pkcs12_info
        krb.subject_base = subject_base
        krb.master_fqdn = master_host_name
        krb.config_pkinit = not no_pkinit

        #krb.__common_setup(realm_name, host_name, domain_name, admin_password)
        krb.fqdn = host_name
        krb.realm = realm_name.upper()
        krb.host = host_name.split(".")[0]
        krb.ip = socket.getaddrinfo(host_name, None, socket.AF_UNSPEC,
                                    socket.SOCK_STREAM)[0][4][0]
        krb.domain = domain_name
        krb.suffix = ipautil.realm_to_suffix(krb.realm)
        krb.kdc_password = ipautil.ipa_generate_password()
        krb.admin_password = admin_password
        krb.dm_password = admin_password

        #krb.__setup_sub_dict()
        if os.path.exists(paths.COMMON_KRB5_CONF_DIR):
            includes = 'includedir {}'.format(paths.COMMON_KRB5_CONF_DIR)
        else:
            includes = ''

        krb.sub_dict = dict(FQDN=krb.fqdn,
                            IP=krb.ip,
                            PASSWORD=krb.kdc_password,
                            SUFFIX=krb.suffix,
                            DOMAIN=krb.domain,
                            HOST=krb.host,
                            SERVER_ID=installutils.realm_to_serverid(
                                krb.realm),
                            REALM=krb.realm,
                            KRB5KDC_KADM5_ACL=paths.KRB5KDC_KADM5_ACL,
                            DICT_WORDS=paths.DICT_WORDS,
                            KRB5KDC_KADM5_KEYTAB=paths.KRB5KDC_KADM5_KEYTAB,
                            KDC_CERT=paths.KDC_CERT,
                            KDC_KEY=paths.KDC_KEY,
                            CACERT_PEM=paths.CACERT_PEM,
                            KDC_CA_BUNDLE_PEM=paths.KDC_CA_BUNDLE_PEM,
                            CA_BUNDLE_PEM=paths.CA_BUNDLE_PEM,
                            INCLUDES=includes)

        # IPA server/KDC is not a subdomain of default domain
        # Proper domain-realm mapping needs to be specified
        domain = dnsname.from_text(krb.domain)
        fqdn = dnsname.from_text(krb.fqdn)
        if not fqdn.is_subdomain(domain):
            logger.debug("IPA FQDN '%s' is not located in default domain '%s'",
                         fqdn, domain)
            server_domain = fqdn.parent().to_unicode(omit_final_dot=True)
            logger.debug("Domain '%s' needs additional mapping in krb5.conf",
                         server_domain)
            dr_map = " .%(domain)s = %(realm)s\n %(domain)s = %(realm)s\n" \
                        % dict(domain=server_domain, realm=krb.realm)
        else:
            dr_map = ""
        krb.sub_dict['OTHER_DOMAIN_REALM_MAPS'] = dr_map

        # Configure KEYRING CCACHE if supported
        if kernel_keyring.is_persistent_keyring_supported():
            logger.debug("Enabling persistent keyring CCACHE")
            krb.sub_dict['OTHER_LIBDEFAULTS'] = \
                " default_ccache_name = KEYRING:persistent:%{uid}\n"
        else:
            logger.debug("Persistent keyring CCACHE is not enabled")
            krb.sub_dict['OTHER_LIBDEFAULTS'] = ''

    return krb
Пример #25
0
def check_dns_resolution(host_name, dns_servers):
    """Check forward and reverse resolution of host_name using dns_servers
    """
    # Point the resolver at specified DNS server
    server_ips = []
    for dns_server in dns_servers:
        try:
            server_ips = list(
                a[4][0] for a in socket.getaddrinfo(dns_server, None))
        except socket.error:
            pass
        else:
            break
    if not server_ips:
        logger.error(
            'Could not resolve any DNS server hostname: %s', dns_servers)
        return False
    resolver = dnsresolver.Resolver()
    resolver.nameservers = server_ips

    logger.debug('Search DNS server %s (%s) for %s',
                 dns_server, server_ips, host_name)

    # Get IP addresses of host_name
    addresses = set()
    for rtype in 'A', 'AAAA':
        try:
            result = resolver.query(host_name, rtype)
        except dnsexception.DNSException:
            rrset = []
        else:
            rrset = result.rrset
        if rrset:
            addresses.update(r.address for r in result.rrset)

    if not addresses:
        logger.error(
            'Could not resolve hostname %s using DNS. '
            'Clients may not function properly. '
            'Please check your DNS setup. '
            '(Note that this check queries IPA DNS directly and '
            'ignores /etc/hosts.)',
            host_name)
        return False

    no_errors = True

    # Check each of the IP addresses
    checked = set()
    for address in addresses:
        if address in checked:
            continue
        checked.add(address)
        try:
            logger.debug('Check reverse address %s (%s)', address, host_name)
            revname = dnsreversename.from_address(address)
            rrset = resolver.query(revname, 'PTR').rrset
        except Exception as e:
            logger.debug('Check failed: %s %s', type(e).__name__, e)
            logger.error(
                'Reverse DNS resolution of address %s (%s) failed. '
                'Clients may not function properly. '
                'Please check your DNS setup. '
                '(Note that this check queries IPA DNS directly and '
                'ignores /etc/hosts.)',
                address, host_name)
            no_errors = False
        else:
            host_name_obj = dnsname.from_text(host_name)
            if rrset:
                names = [r.target.to_text() for r in rrset]
            else:
                names = []
            logger.debug(
                'Address %s resolves to: %s. ', address, ', '.join(names))
            if not rrset or not any(
                    r.target == host_name_obj for r in rrset):
                logger.error(
                    'The IP address %s of host %s resolves to: %s. '
                    'Clients may not function properly. '
                    'Please check your DNS setup. '
                    '(Note that this check queries IPA DNS directly and '
                    'ignores /etc/hosts.)',
                    address, host_name, ', '.join(names))
                no_errors = False

    return no_errors
Пример #26
0
    def main(self, host=[], *args):
        """
        Main function
        """
        target = self.ip

        if self.host:
            try:
                target = gethostbyname(self.host)
            except:
                raise InvalidTarget('Host not found.')

        domain = None

        if not host or not host[0]:
            raise NoHostName('No host name specified.')

        for domain in host:
            if not domain:
                continue

            self._check_stop()

            self._write_result('%s:' % domain)
            results = []

            try:
                # make DNS query manually, clearing the RD (recursion desired) flag
                query = make_query(domain, rdatatype.A, rdataclass.IN)
                query.flags = flags.RD

                found = False

                try:
                    response = dns_query.udp(query, target, self.DNS_TIMEOUT, self.DNS_PORT, None)

                except Exception:
                    response = None

                if response and response.rcode() == rcode.NXDOMAIN:
                    raise NXDOMAIN

                if response and response.rcode() == rcode.NOERROR:
                    found = True
                else:
                    raise NXDOMAIN

                a_records = Answer(dns_name.from_text(domain), rdatatype.A, rdataclass.IN, response, True)
                a_records = map(lambda x: str(x), a_records)

                for a in a_records:
                    if str(a) not in results:
                        results.append(str(a))
                        self._write_result(str(a))

                if len(results) == 0:
                    self._write_result('No A records.')

            except ( NoAnswer, NXDOMAIN ):
                self._write_result('Host not found.')

            except Timeout:
                self._write_result('DNS request timeout.')

            except DNSException:
                self._write_result('DNS error.')

            self._write_result('')

        self._check_stop()