Python dns.zone() Examples

The following are 21 code examples of dns.zone(). 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 , or try the search function .
Example #1
Source File: dnsrecon.py    From Yuki-Chan-The-Auto-Pentest with MIT License 6 votes vote down vote up
def query_ds(target, ns, timeout=5.0):
    """
    Function for performing DS Record queries. Returns answer object. Since a
    timeout will break the DS NSEC chain of a zone walk it will exit if a timeout
    happens.
    """
    try:
        query = dns.message.make_query(target, dns.rdatatype.DS, dns.rdataclass.IN)
        query.flags += dns.flags.CD
        query.use_edns(edns=True, payload=4096)
        query.want_dnssec(True)
        answer = dns.query.udp(query, ns, timeout)
    except dns.exception.Timeout:
        print_error("A timeout error occurred please make sure you can reach the target DNS Servers")
        print_error(
            "directly and requests are not being filtered. Increase the timeout from {0} second".format(timeout))
        print_error("to a higher number with --lifetime <time> option.")
        sys.exit(1)
    except:
        print("Unexpected error: {0}".format(sys.exc_info()[0]))
        raise
    return answer 
Example #2
Source File: test_dnsutils.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_zone_lock(self):
        # Initialize a ZoneLock
        lock = dnsutils.ZoneLock(0.1)

        # Ensure there's no lock for different zones
        for zone_name in ['foo.com.', 'bar.com.', 'example.com.']:
            self.assertTrue(lock.acquire(zone_name))

        # Ensure a lock for successive calls for the same zone
        self.assertTrue(lock.acquire('example2.com.'))
        self.assertFalse(lock.acquire('example2.com.'))

        # Acquire, release, and reacquire
        self.assertTrue(lock.acquire('example3.com.'))
        lock.release('example3.com.')
        self.assertTrue(lock.acquire('example3.com.')) 
Example #3
Source File: dnsutils.py    From designate with Apache License 2.0 6 votes vote down vote up
def acquire(self, zone):
        with self.lock:
            # If no one holds the lock for the zone, grant it
            if zone not in self.data:
                self.data[zone] = time.time()
                return True

            # Otherwise, get the time that it was locked
            locktime = self.data[zone]
            now = time.time()

            period = now - locktime

            # If it has been locked for longer than the allowed period
            # give the lock to the new requester
            if period > self.delay:
                self.data[zone] = now
                return True

            LOG.debug('Lock for %(zone)s can\'t be released for %(period)s'
                      'seconds' % {'zone': zone,
                                   'period': str(self.delay - period)})

            # Don't grant the lock for the zone
            return False 
Example #4
Source File: test_octodns_source_axfr.py    From octodns with MIT License 6 votes vote down vote up
def test_populate(self, from_xfr_mock):
        got = Zone('unit.tests.', [])

        from_xfr_mock.side_effect = [
            self.forward_zonefile,
            DNSException
        ]

        self.source.populate(got)
        self.assertEquals(11, len(got.records))

        with self.assertRaises(AxfrSourceZoneTransferFailed) as ctx:
            zone = Zone('unit.tests.', [])
            self.source.populate(zone)
        self.assertEquals('Unable to Perform Zone Transfer',
                          text_type(ctx.exception)) 
Example #5
Source File: dnsutils.py    From designate with Apache License 2.0 5 votes vote down vote up
def from_dnspython_zone(dnspython_zone):
    # dnspython never builds a zone with more than one SOA, even if we give
    # it a zonefile that contains more than one
    soa = dnspython_zone.get_rdataset(dnspython_zone.origin, 'SOA')
    if soa is None:
        raise exceptions.BadRequest('An SOA record is required')
    if soa.ttl == 0:
        soa.ttl = CONF['service:central'].min_ttl
    email = soa[0].rname.to_text(omit_final_dot=True)
    if six.PY3 and isinstance(email, bytes):
        email = email.decode('utf-8')
    email = email.replace('.', '@', 1)

    name = dnspython_zone.origin.to_text()
    if six.PY3 and isinstance(name, bytes):
        name = name.decode('utf-8')

    values = {
        'name': name,
        'email': email,
        'ttl': soa.ttl,
        'serial': soa[0].serial,
        'retry': soa[0].retry,
        'expire': soa[0].expire
    }

    zone = objects.Zone(**values)

    rrsets = dnspyrecords_to_recordsetlist(dnspython_zone.nodes)
    zone.recordsets = rrsets
    return zone 
Example #6
Source File: libdns.py    From habu with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def axfr(domain):
    """ returns a list with the ns that allows zone transfers"""

    allowed = []

    for server in ns(domain):

        try:
            z = dns.zone.from_xfr(dns.query.xfr(server, domain))
            if z.nodes.keys():
                allowed.append(server)
        except Exception as e:
            pass

    return allowed 
Example #7
Source File: 20_4_dns_zone_transfer.py    From Python-Network-Programming with MIT License 5 votes vote down vote up
def main(address):
    soa_answer = dns.resolver.query(address, 'SOA')
    master_answer = dns.resolver.query(soa_answer[0].mname, 'A')
    try:
        z = dns.zone.from_xfr(dns.query.xfr(master_answer[0].address, address))
        names = z.nodes.keys()
        names.sort()
        for n in names:
            print(z[n].to_text(n))
    except socket.error as e:
        print('Failed to perform zone transfer:', e)
    except dns.exception.FormError as e:
        print('Failed to perform zone transfer:', e) 
Example #8
Source File: _dns.py    From admin4 with Apache License 2.0 5 votes vote down vote up
def GetZone(self, zone):
    xfr = dns.query.xfr(self.server.settings['host'], zone, timeout=self.server.settings.get('timeout', 1.)*10., port=self.server.settings['port'], keyring=self.GetKeyring())
    zoneObj = dns.zone.from_xfr(xfr)
    return zoneObj 
Example #9
Source File: 11_4_dns_zone_transfer.py    From Python-Network-Programming-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
def main(address):
    soa_answer = dns.resolver.query(address, 'SOA')
    master_answer = dns.resolver.query(soa_answer[0].mname, 'A')
    try:
        z = dns.zone.from_xfr(dns.query.xfr(master_answer[0].address, address))
        names = z.nodes.keys()
        names.sort()
        for n in names:
            print(z[n].to_text(n))
    except socket.error as e:
        print('Failed to perform zone transfer:', e)
    except dns.exception.FormError as e:
        print('Failed to perform zone transfer:', e) 
Example #10
Source File: axfr-test.py    From Python-AXFR-Test with MIT License 5 votes vote down vote up
def checkaxfr(domain):
  domain = domain.strip()
  try:
    ns_query = dns.resolver.query(domain,'NS')
    for ns in ns_query.rrset:
      nameserver = str(ns)[:-1]
      if nameserver is None or nameserver == "":
        continue

      try:
        axfr = dns.query.xfr(nameserver, domain, lifetime=5)
        try:
          zone = dns.zone.from_xfr(axfr)
          if zone is None:
            continue
          LOGFILE.write("Success: " + domain + " @ " + nameserver + "\n")
          LOGFILE.flush()
          OUTPUTFILE.write("Success: " + domain + " @ " + nameserver + "\n")
          OUTPUTFILE.flush()
          for name, node in zone.nodes.items():
            rdatasets = node.rdatasets
            for rdataset in rdatasets:
              OUTPUTFILE.write(str(name) + " " + str(rdataset) + "\n")
              OUTPUTFILE.flush()
        except Exception as e:
          continue
      except Exception as e:
        continue
  except Exception as e:
    pass
  LOGFILE.write("Finished: " + domain + "\n")
  LOGFILE.flush() 
Example #11
Source File: axfr.py    From OneForAll with GNU General Public License v3.0 5 votes vote down vote up
def axfr(self, server):
        """
        Perform domain transfer

        :param server: domain server
        """
        logger.log('DEBUG', f'Trying to perform domain transfer in {server} of {self.domain}')
        try:
            xfr = dns.query.xfr(where=server, zone=self.domain,
                                timeout=5.0, lifetime=10.0)
            zone = dns.zone.from_xfr(xfr)
        except Exception as e:
            logger.log('DEBUG', e.args)
            logger.log('DEBUG', f'Domain transfer to server {server} of {self.domain} failed')
            return
        names = zone.nodes.keys()
        for name in names:
            full_domain = str(name) + '.' + self.domain
            subdomain = self.match_subdomains(self.domain, full_domain)
            self.subdomains = self.subdomains.union(subdomain)
            record = zone[name].to_text(name)
            self.results.append(record)
        if self.results:
            logger.log('DEBUG', f'Found the domain transfer record of {self.domain} on {server}')
            logger.log('DEBUG', '\n'.join(self.results))
            self.results = [] 
Example #12
Source File: test_octodns_source_axfr.py    From octodns with MIT License 5 votes vote down vote up
def test_populate(self):
        # Valid zone file in directory
        valid = Zone('unit.tests.', [])
        self.source.populate(valid)
        self.assertEquals(11, len(valid.records))

        # 2nd populate does not read file again
        again = Zone('unit.tests.', [])
        self.source.populate(again)
        self.assertEquals(11, len(again.records))

        # bust the cache
        del self.source._zone_records[valid.name]

        # No zone file in directory
        missing = Zone('missing.zone.', [])
        self.source.populate(missing)
        self.assertEquals(0, len(missing.records))

        # Zone file is not valid
        with self.assertRaises(ZoneFileSourceLoadFailure) as ctx:
            zone = Zone('invalid.zone.', [])
            self.source.populate(zone)
        self.assertEquals('The DNS zone has no NS RRset at its origin.',
                          text_type(ctx.exception))

        # Records are not to RFC (lenient=False)
        with self.assertRaises(ValidationError) as ctx:
            zone = Zone('invalid.records.', [])
            self.source.populate(zone)
        self.assertEquals('Invalid record _invalid.invalid.records.\n'
                          '  - invalid name for SRV record',
                          text_type(ctx.exception))

        # Records are not to RFC, but load anyhow (lenient=True)
        invalid = Zone('invalid.records.', [])
        self.source.populate(invalid, lenient=True)
        self.assertEquals(12, len(invalid.records)) 
Example #13
Source File: lambda_function.py    From aws-lambda-mirror-dns-function with Apache License 2.0 5 votes vote down vote up
def update_resource_record(zone_id, host_name, hosted_zone_name, rectype, changerec, ttl, action):
    if not (rectype == 'NS' and host_name == '@'):
        print 'Updating as %s for %s record %s TTL %s in zone %s with %s ' % (
            action, rectype, host_name, ttl, hosted_zone_name, changerec)
        if rectype != 'SOA':
            if host_name == '@':
                host_name = ''
            elif host_name[-1] != '.':
                host_name += '.'
                # Make Route 53 change record set API call
        dns_changes = {
            'Comment': 'Managed by Lambda Mirror DNS',
            'Changes': [
                {
                    'Action': action,
                    'ResourceRecordSet': {
                        'Name': host_name + hosted_zone_name,
                        'Type': rectype,
                        'ResourceRecords': [],
                        'TTL': ttl
                    }
                }
            ]
        }


        for value in changerec:  # Build the recordset
            if (rectype != 'CNAME' and rectype != 'SRV' and rectype != 'MX' and rectype!= 'NS') or (str(value)[-1] == '.'):
                dns_changes['Changes'][0]['ResourceRecordSet']['ResourceRecords'].append({'Value': str(value)})
            else:
                dns_changes['Changes'][0]['ResourceRecordSet']['ResourceRecords'].append({'Value': str(value) + '.' + hosted_zone_name + '.'})

        try:  # Submit API request to Route 53
            route53.change_resource_record_sets(HostedZoneId=zone_id, ChangeBatch=dns_changes)
        except BaseException as e:
            print e
            sys.exit('ERROR: Unable to update zone %s' % hosted_zone_name)
        return True


# Perform a diff against the two zones and return difference set 
Example #14
Source File: dnsutils.py    From designate with Apache License 2.0 5 votes vote down vote up
def release(self, zone):
        # Release the lock
        with self.lock:
            try:
                self.data.pop(zone)
            except KeyError:
                pass 
Example #15
Source File: test_dnsutils.py    From designate with Apache License 2.0 5 votes vote down vote up
def test_parse_zone(self):
        zone_file = self.get_zonefile_fixture()

        dnspython_zone = dnszone.from_text(
            zone_file,
            # Don't relativize, otherwise we end up with '@' record names.
            relativize=False,
            # Dont check origin, we allow missing NS records (missing SOA
            # records are taken care of in _create_zone).
            check_origin=False
        )

        zone = dnsutils.from_dnspython_zone(dnspython_zone)

        for rrset in zone.recordsets:
            k = (rrset.name, rrset.type)
            self.assertIn(k, SAMPLES)

            sample_ttl = SAMPLES[k].get('ttl', None)
            if rrset.obj_attr_is_set('ttl') or sample_ttl is not None:
                self.assertEqual(sample_ttl, rrset.ttl)

            self.assertEqual(len(rrset.records), len(SAMPLES[k]['records']))

            for record in rrset.records:
                self.assertIn(record.data, SAMPLES[k]['records'])

        self.assertEqual(len(SAMPLES), len(zone.recordsets))
        self.assertEqual('example.com.', zone.name) 
Example #16
Source File: test_dnsutils.py    From designate with Apache License 2.0 5 votes vote down vote up
def test_from_dnspython_zone(self):
        zone_file = self.get_zonefile_fixture()

        dnspython_zone = dnszone.from_text(
            zone_file,
            relativize=False,
            check_origin=False
        )

        zone = dnsutils.from_dnspython_zone(dnspython_zone)

        self.assertIsInstance(zone, objects.zone.Zone) 
Example #17
Source File: dnsrecon.py    From Yuki-Chan-The-Auto-Pentest with MIT License 5 votes vote down vote up
def dns_sec_check(domain, res):
    """
    Check if a zone is configured for DNSSEC and if so if NSEC or NSEC3 is used.
    """
    try:
        answer = res._res.query(domain, 'DNSKEY')
        print_status("DNSSEC is configured for {0}".format(domain))
        nsectype = get_nsec_type(domain, res)
        print_status("DNSKEYs:")
        for rdata in answer:
            if rdata.flags == 256:
                key_type = "ZSK"

            if rdata.flags == 257:
                key_type = "KSk"

            print_status("\t{0} {1} {2} {3}".format(nsectype, key_type, algorithm_to_text(rdata.algorithm),
                                                    dns.rdata._hexify(rdata.key)))

    except dns.resolver.NXDOMAIN:
        print_error("Could not resolve domain: {0}".format(domain))
        sys.exit(1)

    except dns.exception.Timeout:
        print_error("A timeout error occurred please make sure you can reach the target DNS Servers")
        print_error("directly and requests are not being filtered. Increase the timeout from {0} second".format(
            res._res.timeout))
        print_error("to a higher number with --lifetime <time> option.")
        sys.exit(1)
    except dns.resolver.NoAnswer:
        print_error("DNSSEC is not configured for {0}".format(domain)) 
Example #18
Source File: dnsrecon.py    From Yuki-Chan-The-Auto-Pentest with MIT License 5 votes vote down vote up
def in_cache(dict_file, ns):
    """
    Function for Cache Snooping, it will check a given NS server for specific
    type of records for a given domain are in it's cache.
    """
    found_records = []
    with open(dict_file) as f:

        for zone in f:
            dom_to_query = str.strip(zone)
            query = dns.message.make_query(dom_to_query, dns.rdatatype.A, dns.rdataclass.IN)
            query.flags ^= dns.flags.RD
            answer = dns.query.udp(query, ns)
            if len(answer.answer) > 0:
                for an in answer.answer:
                    for rcd in an:
                        if rcd.rdtype == 1:
                            print_status("\tName: {0} TTL: {1} Address: {2} Type: A".format(an.name, an.ttl, rcd.address))

                            found_records.extend([{'type': "A", 'name': an.name,
                                                   'address': rcd.address, 'ttl': an.ttl}])

                        elif rcd.rdtype == 5:
                            print_status("\tName: {0} TTL: {1} Target: {2} Type: CNAME".format(an.name, an.ttl, rcd.target))
                            found_records.extend([{'type': "CNAME", 'name': an.name,
                                                   'target': rcd.target, 'ttl': an.ttl}])

                        else:
                            print_status()
    return found_records 
Example #19
Source File: dnsutils.py    From designate with Apache License 2.0 4 votes vote down vote up
def do_axfr(zone_name, servers, timeout=None, source=None):
    """
    Requests an AXFR for a given zone name and process the response

    :returns: Zone instance from dnspython
    """
    random.shuffle(servers)
    timeout = timeout or CONF["service:mdns"].xfr_timeout

    xfr = None

    for srv in servers:
        to = eventlet.Timeout(timeout)
        log_info = {'name': zone_name, 'host': srv}
        try:
            LOG.info("Doing AXFR for %(name)s from %(host)s", log_info)

            xfr = dns.query.xfr(srv['host'], zone_name, relativize=False,
                                timeout=1, port=srv['port'], source=source)
            raw_zone = dns.zone.from_xfr(xfr, relativize=False)
            break
        except eventlet.Timeout as t:
            if t == to:
                LOG.error("AXFR timed out for %(name)s from %(host)s",
                          log_info)
                continue
        except dns.exception.FormError:
            LOG.error("Zone %(name)s is not present on %(host)s."
                      "Trying next server.", log_info)
        except socket.error:
            LOG.error("Connection error when doing AXFR for %(name)s from "
                      "%(host)s", log_info)
        except Exception:
            LOG.exception("Problem doing AXFR %(name)s from %(host)s. "
                          "Trying next server.", log_info)
        finally:
            to.cancel()
        continue
    else:
        raise exceptions.XFRFailure(
            "XFR failed for %(name)s. No servers in %(servers)s was reached." %
            {"name": zone_name, "servers": servers})

    LOG.debug("AXFR Successful for %s", raw_zone.origin.to_text())

    return raw_zone 
Example #20
Source File: zonetransfer.py    From RTA with Apache License 2.0 4 votes vote down vote up
def zonetransfer(target):
	zonetransfer_list = []
	my_resolver = dns.resolver.Resolver()
	my_resolver.timeout=2.0
	my_resolver.lifetime=2.0
	try:
		answers = my_resolver.query(target,'NS')
	except: 
		response = {'enabled': False, 'list': [] }
		response = json.dumps(response, indent=4, separators=(',', ': '))
		return response
	
	ip_from_nslist = []
	for name_server in answers:
		name_server = str(name_server).rstrip('.')
		ip_from_nslist.append(socket.gethostbyname(name_server))

	for ip_from_ns in ip_from_nslist:
		zone = False

		try:
			zone = dns.zone.from_xfr(dns.query.xfr(ip_from_ns, target))
		except: 
			pass
		
		if zone:
			for name, node in zone.nodes.items():
				rdataset = node.rdatasets
				for record in rdataset:
					name = str(name)
					if name != '@' and name != '*':
						zonetransfer_list.append(name+'.'+target)
	
	if zonetransfer_list:
		zonetransfer_list = [item.lower() for item in zonetransfer_list]
		zonetransfer_list = list(set(zonetransfer_list))
		response = {'enabled': True, 'list': zonetransfer_list }
		response = json.dumps(response, indent=4, separators=(',', ': '))
		return response
	else:
		response = {'enabled': False, 'list': [] }
		response = json.dumps(response, indent=4, separators=(',', ': '))
		return response 
Example #21
Source File: dnsrecon.py    From Yuki-Chan-The-Auto-Pentest with MIT License 4 votes vote down vote up
def usage():
    print("Version: {0}".format(__version__))
    print("Usage: dnsrecon.py <options>\n")
    print("Options:")
    print("   -h, --help                   Show this help message and exit.")
    print("   -d, --domain      <domain>   Target domain.")
    print("   -r, --range       <range>    IP range for reverse lookup brute force in formats (first-last) or in (range/bitmask).")
    print("   -n, --name_server <name>     Domain server to use. If none is given, the SOA of the target will be used.")
    print("   -D, --dictionary  <file>     Dictionary file of subdomain and hostnames to use for brute force.")
    print("   -f                           Filter out of brute force domain lookup, records that resolve to the wildcard defined")
    print("                                IP address when saving records.")
    print("   -t, --type        <types>    Type of enumeration to perform:")
    print("                                std       SOA, NS, A, AAAA, MX and SRV if AXRF on the NS servers fail.")
    print("                                rvl       Reverse lookup of a given CIDR or IP range.")
    print("                                brt       Brute force domains and hosts using a given dictionary.")
    print("                                srv       SRV records.")
    print("                                axfr      Test all NS servers for a zone transfer.")
    print("                                goo       Perform Google search for subdomains and hosts.")
    print("                                snoop     Perform cache snooping against all NS servers for a given domain, testing")
    print("                                          all with file containing the domains, file given with -D option.")
    print("                                tld       Remove the TLD of given domain and test against all TLDs registered in IANA.")
    print("                                zonewalk  Perform a DNSSEC zone walk using NSEC records.")
    print("   -a                           Perform AXFR with standard enumeration.")
    print("   -s                           Perform a reverse lookup of IPv4 ranges in the SPF record with standard enumeration.")
    print("   -g                           Perform Google enumeration with standard enumeration.")
    print("   -w                           Perform deep whois record analysis and reverse lookup of IP ranges found through")
    print("                                Whois when doing a standard enumeration.")
    print("   -z                           Performs a DNSSEC zone walk with standard enumeration.")
    print("   --threads         <number>   Number of threads to use in reverse lookups, forward lookups, brute force and SRV")
    print("                                record enumeration.")
    print("   --lifetime        <number>   Time to wait for a server to response to a query.")
    print("   --db              <file>     SQLite 3 file to save found records.")
    print("   --xml             <file>     XML file to save found records.")
    print("   --iw                         Continue brute forcing a domain even if a wildcard records are discovered.")
    print("   -c, --csv         <file>     Comma separated value file.")
    print("   -j, --json        <file>     JSON file.")
    print("   -v                           Show attempts in the brute force modes.")



# Main
#-------------------------------------------------------------------------------