Exemplo n.º 1
0
    def _manage_record(self, key=None, ttl=None, type=None,
                       zone=None, content=None, action=None):
        """ add or delete a given record
        """

        keyring = dns.tsigkeyring.from_text({
            zone: self.zone_list[zone]['key']
        })

        update = dns.update.Update(
                     zone + '.',
                     keyring=keyring,
                     keyalgorithm=self._select_algorithm(
                         self.zone_list[zone]['algorithm']
                     )
                 )

        if action == 'add':
            ttl = int(ttl)
            content = str(content)
            type = str(type)
            update.add(key, ttl, type, content)
        elif action == 'del':
            type = str(type)
            update.delete(key, type)
        else:
            raise WrongDnsUpdateMethod

        response = dns.query.tcp(update, self.zone_list[zone]['ip'])
Exemplo n.º 2
0
    def remove_record(self):
        result = {'changed': False, 'failed': False}

        if self.record_exists() == 0:
            return result

        # Check mode and record exists, declared fake change.
        if self.module.check_mode:
            self.module.exit_json(changed=True)

        update = dns.update.Update(self.zone,
                                   keyring=self.keyring,
                                   keyalgorithm=self.algorithm)
        update.delete(self.module.params['record'], self.module.params['type'])

        response = self.__do_update(update)
        self.dns_rc = dns.message.Message.rcode(response)

        if self.dns_rc != 0:
            result['failed'] = True
            result['msg'] = "Failed to delete record (rc: %d)" % self.dns_rc
        else:
            result['changed'] = True

        return result
Exemplo n.º 3
0
def dns_do_command(zone, record_name, record_type, command, ttl=0, rdata=""):
    """
    Helper for dns add, update, delete
    """
    # Get the algorithm name from the DNS library (vinylDNS uses "-" in the name and dnspython uses "_")
    algo_name = getattr(dns.tsig,
                        VinylDNSTestContext.dns_key_algo.replace("-", "_"))
    keyring = dns.tsigkeyring.from_text({
        zone["connection"]["keyName"]: (algo_name, VinylDNSTestContext.dns_key)
    })

    (name_server, name_server_port) = dns_server_port(zone)
    fqdn = record_name + "." + zone["name"]
    update = dns.update.Update(zone["name"], keyring=keyring)

    if command == "add":
        update.add(fqdn, ttl, record_type, rdata)
    elif command == "update":
        update.replace(fqdn, ttl, record_type, rdata)
    elif command == "delete":
        update.delete(fqdn, record_type)

    response = dns.query.udp(update,
                             name_server,
                             port=name_server_port,
                             ignore_unexpected=True)
    return response
Exemplo n.º 4
0
    def _update_record(self, identifier, rtype=None, name=None, content=None):
        if self._get_lexicon_option("ttl"):
            ttl = self._get_lexicon_option("ttl")
        else:
            ttl = 300
        if not identifier:
            rrset = self._list_records(rtype, name)
            if len(rrset) == 1:
                identifier = rrset[0]["id"]
            elif len(rrset) < 1:
                raise Exception(
                    "No records found matching type and name - won't update")
            else:
                raise Exception(
                    "Multiple records found matching type and name - won't update"
                )
        d_rtype, d_name, d_content = self._resolve_identifier(identifier)

        if not rtype:
            rtype = d_rtype
        if not name:
            name = d_name

        d_name = dns.name.from_text(d_name).relativize(
            dns.name.from_text(self.zone))
        name = dns.name.from_text(name).relativize(
            dns.name.from_text(self.zone))

        update = dns.update.Update(self.zone, keyring=self.keyring)
        update.delete(d_name, d_rtype, d_content)
        update.add(name, ttl, rtype, content)
        self._run_query(update)
        return True
Exemplo n.º 5
0
def _update_ns(name, addr):
    # name = name.replace('-', '')
    logger.info(f"updating forward zone {name}:{addr} ...")
    update = dns.update.Update("docker",
                               keyring=KEYRING,
                               keyalgorithm=ALGORITHM)
    update.delete(name, "A")
    update.add(name, 60, dns.rdatatype.A, str(addr))
    response = dns.query.tcp(update, DDNS_SERVER)
    if response.rcode() != 0:
        logger.error(f"Failed: {response}")

    rv = str(addr).split(".")
    rv.reverse()
    parts = ".".join(rv[:2])
    zone_name = ".".join(rv[2:]) + ".in-addr.arpa"
    logger.info(f"updating rev zone {zone_name} for {name}...")
    update = dns.update.Update(zone_name,
                               keyring=KEYRING,
                               keyalgorithm=ALGORITHM)
    update.delete(parts, "PTR")
    update.add(parts, 60, dns.rdatatype.PTR, str(name) + ".docker.")
    response = dns.query.tcp(update, DDNS_SERVER)
    if response.rcode() != 0:
        logger.error(f"Failed: {response}")
Exemplo n.º 6
0
    def _submitDNS(self, entries):

        keys = entries.keys()
        keys.sort()

        update = dns.update.Update(self.zone,
                                   keyring=dns.tsigkeyring.from_text(
                                       self.tsig_key))

        update.delete(self.record, 'TXT')

        for k in keys:
            v = entries[k].replace(' ', '\ ')
            update.add(self.record, self.ttl, 'TXT', "%s=%s" % (k, v))

        #print update

        response = dns.query.tcp(update, self.dns_ip)

        #print response

        if response.rcode() != 0:
            raise ValueError("Unexpected Response Code: %s" % response)

        return str(response)
Exemplo n.º 7
0
    def dns_clean_old( self, threshold ):
        """
  
        Issue DNS updates to remove address records which have not been updated since threshold.
        threshold is a gmt time in seconds (as returned by time.now() )

	FIXME: only removes reverse, not fwd.
  
        """
        zone = str(dns.reversename.from_address( self.prefix[0:-4] ))[0:63]
        pfx= int(self.prefix[-2:])
        rzone="%s.ip6.arpa." % zone[-(pfx/2)+1:]
        msgi("dns_clean cycle: ageing threshold: %s seconds " % threshold )
  
        for addr in self.temp_record.keys():
          msgi( "addr=%s, mac=%s, last seen: %s" % ( addr , \
                  self.temp_record[ addr ][1], \
                  time.asctime(time.localtime(self.temp_record[ addr ][0])) ) )
  
          if ( time.time()-threshold > (self.temp_record[ addr ][0]) ):
              update = dns.update.Update( rzone, keyring=self.dnskeyring )
              raddr = dns.reversename.from_address(addr)
              fqdn = dns_rev_host(addr) 
              update.delete( raddr, 'ptr', fqdn )
              response = dns.query.tcp(update,self.dnsmaster)
              if response.rcode() != 0:
                  msge( "removal of reverse registration of %s failed" % addr )
                  msge( response )
              else:
                  msgi( "removal of reverse registration of %s succeeded" % addr )
                  del self.temp_record[ addr ]
              
        self.temp_record.sync()
        self.temp_record.close()
Exemplo n.º 8
0
def make_update(action, query):
    hostname = query.hostname.encode('ascii')
    D = dns.name.from_text(domain)
    H = dns.name.from_text(query.hostname)

    if H.is_subdomain(D):
        R = H.relativize(D)
    else:
        return "400 NOTAUTH %s\n" % H.to_text()

    keyring, algo = read_session_key("/etc/bind/keys/webapp.key")
    update = dns.update.Update(D, keyring=keyring, keyalgorithm=algo)
    if action == 'update':
       update.present(R, 'a')
       update.replace(R, 300, 'a', query.ip.encode('ascii'))
    elif action == 'delete':
       update.present(R, 'a')
       update.delete(R, 'a')
    elif action == 'add':
       update.absent(R, 'a')
       update.add(R, 300, 'a', query.ip.encode('ascii'))
    response = dns.query.tcp(update, '127.0.0.1')

    if response.rcode() == 0:
        return "NOERROR %s\n" % H.to_text()
    else:
        return "%s %s\n" % (dns.rcode.to_text(response.rcode()), H.to_text())
Exemplo n.º 9
0
    def _do_delete_txt(dn):
        domain_list = dn.split('.')
        logger.info(' + Deleting TXT record "%s" for the domain %s' %
                    (token, dn))

        for i in range(0, len(domain_list)):
            head = '.'.join(domain_list[:i])
            tail = '.'.join(domain_list[i:])
            # Attempt to delete the TXT record
            update = dns.update.Update(tail,
                                       keyring=keyring,
                                       keyalgorithm=keyalgorithm)
            update.delete(head, txt_record)
            logger.debug(str(update))
            try:
                response = dns.query.udp(update,
                                         name_server_ip,
                                         timeout=timeout)
                rcode = response.rcode()
                logger.debug(" + Removing TXT record %s -> %s returned %s" %
                             (head, tail, dns.rcode.to_text(rcode)))
                if rcode is dns.rcode.NOERROR:
                    return dn
            except DNSException as err:
                logger.debug("", exc_info=True)
                logger.error("Error deleting TXT record %s %s: %s" %
                             (head, tail, err))
Exemplo n.º 10
0
    def delete(self, container_id):
        LOG.info("Deleting records for container: %s" % container_id)

        uuid_qname = dns.name.from_text(container_id, self._identity)
        identity_rrset = self._query(self._identity, dns.rdatatype.SRV)
        update = dns.update.Update(self._origin, keyring=self._keyring)

        for srv in identity_rrset.get(dns.rdatatype.SRV, []):
            if srv.target == uuid_qname:
                update.delete(self._identity, srv)

        uuid_rdata = self._query(uuid_qname, dns.rdatatype.CNAME, one_record=True)

        if not uuid_rdata:
            LOG.warn("No records found for container: %s" % container_id)
            return

        name_qname = uuid_rdata.target
        name_rrsets = self._query(name_qname, dns.rdatatype.ANY)
        name_rdata = name_rrsets[dns.rdatatype.A].items[0]

        service_name_rdata = name_rrsets[dns.rdatatype.SRV].items[0]
        service_rrsets = self._query(service_name_rdata.target, dns.rdatatype.A)
        service_rdata = service_rrsets.get(dns.rdatatype.A, [])

        update.delete(service_name_rdata.target, dns.rdatatype.A)
        update.delete(uuid_qname, dns.rdatatype.CNAME)
        update.delete(name_qname, dns.rdatatype.A)
        update.delete(name_qname, dns.rdatatype.SRV)

        for rdata in service_rdata:
            if rdata.address != name_rdata.address:
                update.add(service_name_rdata.target, self._ttl, rdata)

        self._update(update)
Exemplo n.º 11
0
    def _cleanup_single(self, achall):
        response, validation = achall.response_and_validation()
        zone, record = self.zone_and_record(achall.domain, achall.validation_domain_name(achall.domain))

        update = dns.update.Update(zone, keyring=self.keyring, keyalgorithm=self.keyalgorithm)
        update.delete(record, 'TXT', validation.encode('ascii'))
        dns.query.tcp(update, self.conf('nameserver'))
Exemplo n.º 12
0
    def _submitDNS(self, entries):

        keys = entries.keys()
        keys.sort()

        update = dns.update.Update(
            self.zone,
            keyring=dns.tsigkeyring.from_text(self.tsig_key))

        update.delete(self.record, 'TXT')

        for k in keys:
            v = entries[k].replace(' ', '\ ')
            update.add(self.record, self.ttl, 'TXT', "%s=%s" % (k, v))

        #print update

        response = dns.query.tcp(update, self.dns_ip)

        #print response

        if response.rcode() != 0:
            raise ValueError("Unexpected Response Code: %s" % response)

        return str(response)
Exemplo n.º 13
0
    def del_txt_record(self, record_name, record_content):
        """
        Delete a TXT record using the supplied information.

        :param str record_name: The record name (typically beginning with '_acme-challenge.').
        :param str record_content: The record content (typically the challenge validation).
        :param int record_ttl: The record TTL (number of seconds that the record may be cached).
        :raises certbot.errors.PluginError: if an error occurs communicating with the DNS server
        """

        domain = self._find_domain(record_name)

        n = dns.name.from_text(record_name)
        o = dns.name.from_text(domain)
        rel = n.relativize(o)

        update = dns.update.Update(domain,
                                   keyring=self.keyring,
                                   keyalgorithm=self.algorithm)
        update.delete(rel, dns.rdatatype.TXT, record_content)

        try:
            response = dns.query.tcp(update, self.server,
                                     self._default_timeout, self.port)
        except Exception as e:
            raise errors.PluginError(
                'Encountered error deleting TXT record: {0}'.format(e))
        rcode = response.rcode()

        if rcode == dns.rcode.NOERROR:
            logger.debug('Successfully deleted TXT record %s', record_name)
        else:
            raise errors.PluginError(
                'Received response from server: {0}'.format(
                    dns.rcode.to_text(rcode)))
Exemplo n.º 14
0
def dockerddns(action, event, dnsserver=config['dockerddns']['dnsserver'], ttl=60):
    update = dns.update.Update(config['dockerddns']['zonename'], keyring=keyring, keyname=config['dockerddns']['keyname'])
    if (action == 'start' and event['ip'] != '0.0.0.0' ):
        logging.debug('[%s] Updating dns %s , setting %s.%s to %s' % (event['name'], dnsserver, event['hostname'], config['dockerddns']['zonename'],event['ip']))
        update.replace(event['hostname'], ttl, 'A', event['ip'])
    elif (action == 'die' ):
        logging.debug('[%s] Removing entry for %s.%s in %s' % (event['name'], event['hostname'], config['dockerddns']['zonename'], dnsserver))
        update.delete(event['hostname'])
    try:
      response = dns.query.tcp(update, dnsserver, timeout=10)
    except (socket.error, dns.exception.Timeout):
      logging.debug('Timeout updating DNS')
      response = 'Timeout Socket'
      pass
    except dns.query.UnexpectedSource:
      logging.debug('Unexpected Source')
      response = 'UnexpectedSource'
      pass
    except dns.tsig.PeerBadKey:
      logging.debug('Bad Key for DNS, Check your config files')
      response = "BadKey"
      pass

    if response.rcode() != 0: 
      logging.error("[%s] Error Reported while updating %s (%s/%s)" % (event['name'],event['hostname'],dns.rcode.to_text(response.rcode()), response.rcode()))
def delFWD(name,ipaddress):
	name = str(name)
	ipaddress = str(ipaddress)
	update = dns.update.Update(splitFQDN(name)[1])
	hostname = splitFQDN(name)[0]
	domain = (splitFQDN(name)[1]).rstrip('.')
	log.debug ('[delFWD] - name %s' % name)
	log.debug ('[delFWD] - ipaddress %s' % ipaddress)
	log.debug ('[delFWD] - hostname %s' % hostname)
	log.debug ('[delFWD] - domainname %s' % domain)
	check4TSIG = TSIGSecured(domain)
	if check4TSIG.isSecure(domain):
		key = str(check4TSIG.TSIG(domain))
		keyname = domain.replace(".","_")
		keyring = dns.tsigkeyring.from_text({keyname:key})
		update = dns.update.Update(splitFQDN(name)[1], keyring=keyring)
	else:
		update = dns.update.Update(splitFQDN(name)[1])
	address_type = enumIPtype(ipaddress)
	if address_type == 4:
		update.delete(hostname, 'A', ipaddress)
	if address_type == 6:
		update.delete(hostname, 'AAAA', ipaddress)	
	response = dns.query.udp(update, monitor_nameserver)
	return response
Exemplo n.º 16
0
    def _manage_record(self,
                       key=None,
                       ttl=None,
                       type=None,
                       zone=None,
                       content=None,
                       action=None):
        """ add or delete a given record
        """

        keyring = dns.tsigkeyring.from_text(
            {zone: self.zone_list[zone]['key']})

        update = dns.update.Update(zone + '.',
                                   keyring=keyring,
                                   keyalgorithm=self._select_algorithm(
                                       self.zone_list[zone]['algorithm']))

        if action == 'add':
            ttl = int(ttl)
            content = str(content)
            type = str(type)
            update.add(key, ttl, type, content)
        elif action == 'del':
            type = str(type)
            update.delete(key, type)
        else:
            raise WrongDnsUpdateMethod

        response = dns.query.tcp(update, self.zone_list[zone]['ip'])
Exemplo n.º 17
0
    def dns_clean_old(self, threshold):
        """
  
        Issue DNS updates to remove address records which have not been updated since threshold.
        threshold is a gmt time in seconds (as returned by time.now() )

	FIXME: only removes reverse, not fwd.
  
        """
        zone = str(dns.reversename.from_address(self.prefix[0:-4]))[0:63]
        pfx = int(self.prefix[-2:])
        rzone = "%s.ip6.arpa." % zone[-(pfx / 2) + 1:]
        msgi("dns_clean cycle: ageing threshold: %s seconds " % threshold)

        for addr in self.temp_record.keys():
            msgi( "addr=%s, mac=%s, last seen: %s" % ( addr , \
                    self.temp_record[ addr ][1], \
                    time.asctime(time.localtime(self.temp_record[ addr ][0])) ) )

            if (time.time() - threshold > (self.temp_record[addr][0])):
                update = dns.update.Update(rzone, keyring=self.dnskeyring)
                raddr = dns.reversename.from_address(addr)
                fqdn = dns_rev_host(addr)
                update.delete(raddr, 'ptr', fqdn)
                response = dns.query.tcp(update, self.dnsmaster)
                if response.rcode() != 0:
                    msge("removal of reverse registration of %s failed" % addr)
                    msge(response)
                else:
                    msgi("removal of reverse registration of %s succeeded" %
                         addr)
                    del self.temp_record[addr]

        self.temp_record.sync()
        self.temp_record.close()
Exemplo n.º 18
0
    def del_txt_record(self, domain_name, record_name, record_content):
        """
        Delete a TXT record using the supplied information.

        :param str domain: The domain to use to find the closest SOA.
        :param str record_name: The record name (typically beginning with '_acme-challenge.').
        :param str record_content: The record content (typically the challenge validation).
        :param int record_ttl: The record TTL (number of seconds that the record may be cached).
        :raises certbot.errors.PluginError: if an error occurs communicating with the DNS server
        """

        domain = self._find_domain(domain_name)

        n = dns.name.from_text(record_name)
        o = dns.name.from_text(domain)
        rel = n.relativize(o)

        update = dns.update.Update(
            domain,
            keyring=self.keyring,
            keyalgorithm=self.algorithm)
        update.delete(rel, dns.rdatatype.TXT, record_content)

        try:
            response = dns.query.tcp(update, self.server)
        except Exception as e:
            raise errors.PluginError('Encountered error deleting TXT record: {0}'
                                     .format(e))
        rcode = response.rcode()

        if rcode == dns.rcode.NOERROR:
            logger.debug('Successfully deleted TXT record')
        else:
            raise errors.PluginError('Received response from server: {0}'
                                     .format(dns.rcode.to_text(rcode)))
Exemplo n.º 19
0
 def delete_txt(self):
     try:
         update = dns.update.Update(self.get_domain_fqdn(), keyring=self.__keyring)
         update.delete(self.__hostname, 'TXT')
         return dns.query.tcp(update, self.__server_ip).rcode()
     except Exception, error:
         raise Exception("Error deleting DNS TXT Entry: %s" % (error))
Exemplo n.º 20
0
def dns_do_command(zone, record_name, record_type, command, ttl=0, rdata=""):
    """
    Helper for dns add, update, delete
    """
    keyring = dns.tsigkeyring.from_text(
        {zone['connection']['keyName']: VinylDNSTestContext.dns_key})

    name_server, name_server_port = dns_server_port(zone)

    fqdn = record_name + "." + zone['name']

    print "updating " + fqdn + " to have data " + rdata

    update = dns.update.Update(zone['name'], keyring=keyring)
    if (command == 'add'):
        update.add(fqdn, ttl, record_type, rdata)
    elif (command == 'update'):
        update.replace(fqdn, ttl, record_type, rdata)
    elif (command == 'delete'):
        update.delete(fqdn, record_type)

    response = dns.query.udp(update,
                             name_server,
                             port=name_server_port,
                             ignore_unexpected=True)
    return response
Exemplo n.º 21
0
 def delete_ptr(self, ip_address):
     name, zone = str(dns.reversename.from_address(ip_address)).split(
         '.', 1)
     update = dns.update.Update(zone,
                                keyring=self.keyring,
                                keyalgorithm=HMAC_MD5)
     update.delete(name)
     dns.query.tcp(update, self.dns_hostname)
Exemplo n.º 22
0
 def update_ds(self, name, ds_set):
     update = self._init_update()
     name = dns.name.from_text(name)
     update.delete(name, dns.rdatatype.DS)
     for ds in ds_set:
         update.add(name, self._ttl, dns.rdatatype.DS, ds)
     response = dns.query.tcp(update, self._server, port=self._port)
     return response.rcode() == 0
Exemplo n.º 23
0
    def delete(self, domain=""):
        if domain == "":
            return False

        update = dns.update.Update('flashhold.com', keyring=self.keyring)
        update.delete(domain, 'A')
        response = dns.query.tcp(update, settings.DNS_HOST)
        print response
Exemplo n.º 24
0
 def _delete_record(self, qtype, fqdn, data, do_ptr):
     log.debug('DDNS delete for record {}, fqdn: {}'.format(qtype, fqdn))
     origin, name = self._parse_name(fqdn)
     update = dns.update.Update(origin, keyring=self.keyring)
     update.delete(name)
     self._do_update(update)
     if do_ptr:
         self._del_ptr(fqdn, data)
Exemplo n.º 25
0
 def update_ds(self, name, ds_set):
     update = self._init_update()
     name = dns.name.from_text(name)
     update.delete(name, dns.rdatatype.DS)
     for ds in ds_set:
         update.add(name, self._ttl, dns.rdatatype.DS, ds)
     response = dns.query.tcp(update, self._server, port=self._port)
     return response.rcode() == 0
Exemplo n.º 26
0
 def dns_push(self, logid, fqdn, v4_addrs = [], v6_addrs = [], cname = None):
     """
     Push a set of A and AAAA records to the DNS, but only if they've
     changed.
     """
     # check if there are any changes, sort the addresses first so that
     # scoring order changes do not cause cache misses
     v4_addrs = sorted(v4_addrs)
     v6_addrs = sorted(v6_addrs)
     if cname != None:
         cache_key = "CNAME " + cname
         v4_addrs = v6_addrs = []
     else:
         cache_key = ' '.join(v4_addrs) + ' ' + ' '.join(v6_addrs)
     
     if self.dns_update_cache.get(fqdn) == cache_key:
         #self.log.info("DNS push [%s]: %s - no changes", logid, fqdn)
         return
         
     self.dns_update_cache[fqdn] = cache_key
     
     # look up the zone file to update
     zone = self.dns_pick_zone(fqdn)
     if zone == None:
         self.log.info("DNS push [%s]: %s is not in a managed zone, not updating", logid, fqdn)
         return
     
     # add a dot to make sure bind doesn't add the zone name in the end
     fqdn = fqdn + '.'
     
     self.log.info("DNS pushing [%s]: %s: %s", logid, fqdn, cache_key)
     
     update = dns.update.Update(zone, keyring=self.dns_keyring, keyalgorithm="hmac-sha256")
     update.delete(fqdn)
     if cname != None:
         update.add(fqdn, self.dns_ttl, 'cname', cname + '.')
     else:
         for a in v4_addrs:
             update.add(fqdn, self.dns_ttl, 'a', a.encode('ascii'))
         for a in v6_addrs:
             update.add(fqdn, self.dns_ttl, 'aaaa', a.encode('ascii'))
     
     try:
         response = dns.query.tcp(update, self.dns_master)
     except socket.error as e:
         self.log.error("DNS push [%s]: update error, cannot connect to DNS master: %r", logid, e)
         return
     except dns.tsig.PeerBadKey as e:
         self.log.error("DNS push [%s]: update error, DNS master does not accept our key: %r", logid, e)
         return
     except Exception as e:
         self.log.error("DNS push [%s]: update error: %r", logid, e)
         return
         
     self.log.info("DNS push [%s]: Sent %s: %s - response: %s / %s", logid, zone, fqdn,
         dns.opcode.to_text(dns.opcode.from_flags(response.flags)),
         dns.rcode.to_text(dns.rcode.from_flags(response.flags, response.ednsflags))
         )
Exemplo n.º 27
0
def delete_dns_record(host, domain, ip):
    PRIMARY_DNS_SERVER_IP = '192.168.8.200'

    keyring = dns.tsigkeyring.from_text({
        "dynamic.vmware.haf.":
        "jn694IwJ9IP4i5yGtSdIZJTFeFpVEvK2wa78gHVX8PohLNBQVYQd+JyGNX8A3hju8WmsNVo1Oq58YS93HR4HIQ=="
    })

    dns_domain = '%s.' % (domain)

    logging.debug("DNS records A")
    logging.debug(" {} ({})".format(host, ip))
    update = dns.update.Update(zone=dns_domain,
                               keyname='dynamic.vmware.haf.',
                               keyring=keyring,
                               keyalgorithm=dns.tsig.HMAC_SHA512)

    update.delete(host, 'A')
    response = dns.query.tcp(update, PRIMARY_DNS_SERVER_IP)
    flags = dns.flags.to_text(response.flags)
    logging.debug(" A   DNS delete response: {} {}".format(
        dns.rcode.to_text(response.rcode()), flags))

    update.delete(host, 'TXT')
    response = dns.query.tcp(update, PRIMARY_DNS_SERVER_IP)
    flags = dns.flags.to_text(response.flags)
    logging.debug(" TXT DNS delete response: {} {}".format(
        dns.rcode.to_text(response.rcode()), flags))

    if ip:
        ### Create reverse entry (PTR)
        # Neat function to generate a reverse entry
        reventry = dns.reversename.from_address(ip)
        revzone = ''
        # Specify the reverse lookup zone based on the reverse IP address.
        # The labels[X:] property allows you to specify which octet to use.
        # e.g. 3: will apply the record to the 10.in-addr.arpa zone,
        # whereas 1: will apply it to the 72.23.10.in-addr.arpa zone
        revzone = b'.'.join(dns.name.from_text(str(reventry)).labels[1:])  #
        revzone = revzone.decode()
        # Prepare the payload for the DNS record update
        raction = dns.update.Update(zone=revzone,
                                    keyname='dynamic.vmware.haf.',
                                    keyring=keyring,
                                    keyalgorithm=dns.tsig.HMAC_SHA512)

        # Although we are updating the reverse lookup zone,
        # the record needs to point back to the ‘test.example.com’ domain, not the 10.in-addr.arpa domain
        host_fqdn = '%s.%s' % (host, dns_domain)
        # Inject the updated record details into the the class, preparing for submission to the DNS server
        raction.delete(reventry, dns.rdatatype.PTR)
        # submit the new record to the DNS server to apply the update
        response = dns.query.tcp(raction, PRIMARY_DNS_SERVER_IP, timeout=5)
        flags = dns.flags.to_text(response.flags)
        logging.debug(" PTR DNS delete response: {} {}".format(
            dns.rcode.to_text(response.rcode()), flags))
Exemplo n.º 28
0
def domain_delete(domain, ip):
	answer = dns.resolver.query(domain + ".lan", "a")
	for record in answer:
		if record.address == ip:
			break
	else:
		return
	update = dns.update.Update("lan")
	update.delete(domain, "a")
	dns.query.tcp(update, "127.0.0.1")
Exemplo n.º 29
0
def domain_delete(domain, ip):
    answer = dns.resolver.query(domain + ".lan", "a")
    for record in answer:
        if record.address == ip:
            break
    else:
        return
    update = dns.update.Update("lan")
    update.delete(domain, "a")
    dns.query.tcp(update, "127.0.0.1")
Exemplo n.º 30
0
 def del_record(self, domain_zone, domain_name, record_type):
     update = dns.update.Update(domain_zone,
                                keyring=self.keyring,
                                keyalgorithm=self.sha_type)
     update.delete(domain_name)
     dns.query.tcp(update, self.name_server_addr)
     if self.search_record(domain_name + '.' + domain_zone, record_type):
         return {'code': 3, 'message': 'not delete sucess'}
     else:
         return {'code': '0', 'message': 'ok'}
Exemplo n.º 31
0
def dockerbind(action, event, config):
    """
    This will update a zone in a bind dns configured for dynamic updates
    """
    dnsserver = config['dnsserver']
    ttl = config['ttl']
    port = config['dnsport']
    update = dns.update.Update(config['zonename'],
                               keyring=config['keyring'],
                               keyname=config['keyname'])
    #logging.debug('EVENT: %s', event)
    try:
        if "srvrecords" in event:
            srvrecords = event["srvrecords"].split()
            for srv in srvrecords:
                values = srv.split("#")
                #print("%s %s\n" % (values, event['hostname']))

        if action == 'start' and event['ip'] != '0.0.0.0':
            update.replace(event['hostname'], ttl, 'A', event['ip'])
            if event['ipv6'] != '':
                update.replace(event['hostname'], ttl, 'AAAA', event['ipv6'])
                logging.info(
                    '[%s] Updating dns %s , setting %s.%s to %s and %s',
                    event['name'], dnsserver, event['hostname'],
                    config['zonename'], event['ip'], event['ipv6'])
            else:
                logging.info('[%s] Updating dns %s , setting %s.%s to %s',
                             event['name'], dnsserver, event['hostname'],
                             config['zonename'], event['ip'])

        elif action == 'die':
            logging.info('[%s] Removing entry for %s.%s in %s', event['name'],
                         event['hostname'], config['zonename'], dnsserver)
            update.delete(event['hostname'])

        response = dns.query.tcp(update, dnsserver, timeout=10, port=port)
        if response.rcode() != 0:
            logging.error("[%s] Error Reported while updating %s (%s/%s)",
                          event['name'], event['hostname'],
                          dns.rcode.to_text(response.rcode()),
                          response.rcode())
    except (socket.error, dns.exception.Timeout):
        logging.error('Timeout updating DNS')
        response = 'Timeout Socket'
    except dns.query.UnexpectedSource:
        logging.error('Unexpected Source')
        response = 'UnexpectedSource'
    except dns.exception.SyntaxError:
        logging.error('Missing parameters to update DNS')
    except dns.tsig.PeerBadKey:
        logging.error('Bad Key for DNS, Check your config files')
        response = "BadKey"
    return event
Exemplo n.º 32
0
    def fx_agent_dynrec(self, operation, domain, nssrv, selector, ttl,
                        payload_b64, **tsig):
        """ Manage Agent Dynamic DNS Record: CRUD"""

        self.flogger.debug(
            "Accepted for record: {0}, {1}, {2}, {3}, {4}, {5}, {6}".format(
                operation, domain, nssrv, selector, ttl, payload_b64, tsig))

        keyring = dns.tsigkeyring.from_text(tsig)

        self.flogger.debug("DNS TSIG Keyring: " + str(keyring))
        update = dns.update.Update(domain,
                                   keyring=keyring,
                                   keyalgorithm=HMAC_SHA256)
        self.flogger.debug("DNS TXT Update: " + str(update))

        # Make DKIM record look normal
        dkim_record = '"v=DKIM1; h=sha256; k=rsa; t=y; s=email; p={0}"'.format(
            payload_b64)

        # From http://www.dnspython.org/docs/1.14.0/dns.update.Update-class.html#add
        if operation == 'add':
            self.flogger.debug("DNS: Adding TXT record")
            update.add(selector, ttl, dns.rdatatype.TXT, dkim_record)
        else:
            if operation == 'update':
                self.flogger.debug("DNS: Updating TXT record")
                update.replace(selector, ttl, dns.rdatatype.TXT, dkim_record)
            else:
                if operation == 'delete':
                    self.flogger.debug("DNS: Deleting TXT record")
                    update.delete(selector)
                else:
                    self.flogger.error("DNS: Invalid record action: " +
                                       operation)
                    raise ValueError(
                        "Operation must be one of <add|update|delete>")

        try:
            response = dns.query.tcp(update, nssrv, timeout=10)
            if response.rcode() == 0:
                self.flogger.debug("DynDNS: Update Successful")
                return True
            else:
                self.flogger.error("DynDNS: Update failed: code: {0}".format(
                    response.rcode()))
                self.flogger.error("Response: {0}".format(response))
                return False
        except dns.tsig.PeerBadKey as peerkey:
            self.flogger.error("DNS TSIG: Bad Peer key {0}".format(peerkey))
            return False
        except Exception as e:
            self.flogger.error("DNS: General Exception {0}".format(e))
            return False
    def remove_record(self):
        update = dns.update.Update(self.zone,
                                   keyring=self.keyring,
                                   keyalgorithm=self.algorithm)
        update.delete(self.record, self.type)

        response = self.__do_update(update)
        if dns.message.Message.rcode(response) == 0:
            return True
        else:
            return False
Exemplo n.º 34
0
    def remove_record(self):
        update = dns.update.Update(self.zone, keyring=self.keyring)
        update.delete(self.record, self.type)

        try:
            response = dns.query.tcp(update, self.server, timeout=10)
            if dns.message.Message.rcode(response) == 0:
                return True
            else:
                return False
        except:
            self.module.fail_json(msg='Connection to DNS server failed')
Exemplo n.º 35
0
 def delete_rev(self):
     try:            
         name = self.validate_rev_name()
         if not name:
             return None
         
         update = dns.update.Update(self.get_rev_domain_fqdn(), keyring=self.__keyring)
         update.present(name, 'PTR', self.get_fqdn())
         update.delete(name, 'PTR')
         return dns.query.tcp(update, self.__server_ip).rcode()
     except Exception, error:
         raise Exception("Error deleting DNS PTR Entry: %s" % (error))
Exemplo n.º 36
0
    def remove_record(self):
        update = dns.update.Update(self.zone, keyring=self.keyring)
        update.delete(self.record, self.type)

        try:
            response = dns.query.tcp(update, self.server, timeout=10)
            if dns.message.Message.rcode(response) == 0:
                return True
            else:
                return False
        except:
            self.module.fail_json(msg="Connection to DNS server failed")
Exemplo n.º 37
0
    def delete(self, hostname):

        try:

            update = dns.update.Update(self.zone, keyring=self.keyring)
            update.delete(self._hostname(hostname))
            response = dns.query.tcp(update, self.nshost)

        except Exception as e:

            logging.LogError("Could not update hostname %s: %s" %
                             (hostname, e))
Exemplo n.º 38
0
 def remove_dns_record(self, domain, txtvalue):
     zone, nameserverip = self._determine_zone_and_nameserverip(domain)
     update = dns.update.Update(zone,
                                keyring=self.keyring,
                                keyalgorithm=self.keyalgorithm)
     update.delete(
         domain,
         dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.TXT,
                             txtvalue))
     print('Deleting \'{} 60 IN TXT "{}"\' from {}'.format(
         domain, txtvalue, nameserverip))
     dns.query.tcp(update, nameserverip)
Exemplo n.º 39
0
def doUpdate(args):
    # Sanity check the data and get the action and record type
    action, _type = verify_input(my_input)
    ttl = is_valid_TTL(TimeToLive)
    # Get the hostname and the origin
    Origin, name = parse_name(Origin, my_input[1])
    # Validate and setup the Key
    keyring, keyalgo = get_key(KeyFile)
    # Start constructing the DDNS Query
    update = dns.update.Update(Origin, keyring=keyring,
                               keyalgorithm=getattr(dns.tsig, keyalgo))
    # Put the payload together.
    my_payload = ''  # Start with an empty payload.
    do_ptr = doPTR

    if _type == 'A' or _type == 'AAAA':
        my_payload = my_input[3]
        if doPTR == True:
            ptr_target = name.to_text() + '.' + Origin.to_text()
            ptr_origin, ptr_name = parse_name(None, genPTR(my_payload).to_text())
            ptr_update = dns.update.Update(ptr_origin, keyring=keyring)
    if action != 'del' and _type == 'CNAME' or _type == 'NS' or _type == 'TXT' or _type == 'PTR':
        my_payload = my_input[3]
        do_ptr = False
    elif type == 'SRV':
        my_payload = my_input[3] + ' ' + my_input[4] + ' ' + my_input[5] + ' ' + my_input[6]
        do_ptr = False
    elif type == 'MX':
        my_payload = my_input[3]+' '+my_input[4]
        do_ptr = False
    elif type == 'CNAME':
        do_ptr = False
    # Build the update
    if action == 'add':
        update.add(name, ttl, _type, my_payload)
        if do_ptr is True and _type:
            ptr_update.add(ptr_name, ttl, 'PTR', ptr_target)
    elif action == 'delete' or action == 'del':
        if my_payload != '':
            update.delete(name, _type, my_payload)
        else:
            update.delete(name)

        if do_ptr is True and (_type == 'A' or _type == 'AAAA'):
            ptr_update.delete(ptr_name, 'PTR', ptr_target)
        else:
            do_ptr = False
    elif action == 'update':
        update.replace(name, ttl, _type, my_payload)
        if doPTR is True:
            ptr_update.replace(ptr_name, ttl, 'PTR', ptr_target)
Exemplo n.º 40
0
 def update_dns_value(self, sqlobject, delete=False):
     """Update dns value
     if delete is true, delete value instead of adding"""
     self.create_keyring()
     domain = self.get_domain(sqlobject.t_domains_id)
     if not domain:
         if delete:
             # domain already deleted
             return True
         self.log.error('Cannot get domain for t_domains_id %s' % sqlobject.t_domains_id)
         return False
     if self.parse_inetlist(domain.masters):
         # this server is not master
         return True
     if not self.conf.bind_master:
         # this server is not master
         return True
     value = str(sqlobject.value).split('/')[0]
     update = dns.update.Update(str(domain.name), keyring=self.keyring,
                 keyalgorithm=str(self.conf.bind_secret_algorithm).lower())
     if delete:
         update.delete(str(sqlobject.key), str(sqlobject.type), value)
     else:
         if not self.check_record(sqlobject.key, sqlobject.type, sqlobject.value, domain.name):
             update.add(str(sqlobject.key), int(sqlobject.ttl),
                                             str(sqlobject.type), value)
         else:
             self.log.debug('Record %s %d IN %s %s already exists' % (
                                 str(sqlobject.key), int(sqlobject.ttl),
                                 str(sqlobject.type), value))
             return True
     try:
         response = dns.query.tcp(update, '127.0.0.1')
     except PeerBadKey or PeerBadSignature:
         self.log.error('Cannot update dns entry, secret invalid')
         return False
     if response.rcode() != 0:
         self.log.error('DNS update failed, got error %s on domain %s' % (
                         dns.rcode.to_text(response.rcode()), domain.name))
         return False
     if delete:
         self.log.info('Successfully deleted dns-record %s %d IN %s %s' % (
                                 str(sqlobject.key), int(sqlobject.ttl),
                                 str(sqlobject.type), value))
     else:
         self.log.info('Successfully added dns-record %s %d IN %s %s' % (
                                 str(sqlobject.key), int(sqlobject.ttl),
                                 str(sqlobject.type), value))
     return True
Exemplo n.º 41
0
def _prepare_dns_updates(add_rrsets, delete_rrsets, my_zones):
    """Prepare a set of DNS updates for the specified rrset additions and deletions.
    
    One update will be created for each zone mentioned in the rrsets.  
    Constrints will be added to the DNS update message:
    
      * when deleting the record, ensure that it existed
      * when adding a record, ensure that it did not exist
      * when modifying (deleting and readding) a record, ensure that it existed
    
    Returns a dict mapping zone names to dnspython Update objects.
    """
    
    updates = {}
    
    for rrset in delete_rrsets:
        zone = _get_zone(rrset.name, my_zones)
        
        # Create a new update for this zone if necessary
        if zone not in updates:
            updates[zone] = dns.update.Update(zone, keyring=_create_keyring(zone))
        
        update = updates[zone]
        
        # Require the record exist before deleting it.
        update.present(rrset.name, *rrset.items)
        
        # Delete the record.
        update.delete(rrset.name, rrset)
        
    for rrset in add_rrsets:
        zone = _get_zone(rrset.name, my_zones)
        
        # Create a new update for this zone if necessary
        if zone not in updates:
            updates[zone] = dns.update.Update(zone, keyring=_create_keyring(zone))
        
        update = updates[zone]
        
        # For additions only, require that the record not exist before adding 
        # it.  We're processing each modification as a delete/add pair, so 
        # it will exist before the update (and we ensure this above).
        
        if rrset.name not in [delete.name for delete in delete_rrsets]:
            update.absent(rrset.name, rrset.rdtype)
        
        update.add(rrset.name, rrset)
    
    return updates
Exemplo n.º 42
0
def del_zone():

    # domain:
    d, i = sys.argv[1], sys.argv[2]

    # Update catalog zone
    update = dns.update.Update(CATZONE)
    update.delete('%s.zones' % i)
    response = dns.query.tcp(update, MASTER, port=DNSPORT)
    if response.rcode() != 0:
        raise Exception("Error updating catalog zone: %s" % response.rcode())

    # Delete zone from master using RNDC
    r = isc.rndc((MASTER, RNDCPORT), RNDCALGO, RNDCKEY)
    response = r.call('delzone -clean %s' % d)
Exemplo n.º 43
0
    def modify_record(self):
        update = dns.update.Update(self.zone, keyring=self.keyring, keyalgorithm=self.algorithm)
        update.delete(self.module.params['record'], self.module.params['type'])
        for entry in self.module.params['value']:
            try:
                update.add(self.module.params['record'],
                           self.module.params['ttl'],
                           self.module.params['type'],
                           entry)
            except AttributeError:
                self.module.fail_json(msg='value needed when state=present')
            except dns.exception.SyntaxError:
                self.module.fail_json(msg='Invalid/malformed value')
        response = self.__do_update(update)

        return dns.message.Message.rcode(response)
Exemplo n.º 44
0
 def cleanup(self):
     for key_spec, zone, server, name in self.records:
         keyring = dns.tsigkeyring.from_text({key_spec.id: key_spec.secret})
         update = dns.update.Update(zone,
                                    keyring=keyring,
                                    keyalgorithm=key_spec.algorithm)
         update.delete(name)
         try:
             log.debug('remove dns record "%s" from %s using key %s', name,
                       server, key_spec.id)
             response = dns.query.tcp(update, server[0], port=server[1])
             if response.rcode() != dns.rcode.NOERROR:
                 log.warning('[%s.%s] DNS record cleanup failed: %s', name,
                             zone, dns.rcode.to_text(response.rcode()))
         except Exception as ex:
             log.warning('[%s.%s] DNS record cleanup failed: %s', name,
                         zone, str(ex))
Exemplo n.º 45
0
def delete_Record(server, zone, record_name, record_type, record_data,
                  key_name):
    try:
        transfer_key = models.Key.objects.filter(name=key_name)[0]
    except models.Key.DoesNotExist as exc:
        logging.error(exc)
        raise KeyringException("The specified TSIG key %s does not exist in"
                               "binders configunation" % key_name)
    else:
        algorithm = str(transfer_key.data)

    keyring = dns.tsigkeyring.from_text({str(key_name): algorithm})
    update = dns.update.Update(str(zone), keyring=keyring)
    update.delete(str(record_name), str(record_type), str(record_data))
    output = send_dns_update(update, str(server), str(key_name))
    # response=dns.query.tcp(update,str(server))
    return output
Exemplo n.º 46
0
    def _submitDNS(self, value):

        update = dns.update.Update(
            self.zone,
            keyring=dns.tsigkeyring.from_text(self.tsig_key))

        update.delete(self.record, self.type)
        update.add(self.record, self.ttl, self.type, "%s" % value)
        #print update

        response = dns.query.tcp(update, self.dns_ip)
        #print response

        #if response.rcode() != 0:
            #raise ValueError("Unexpected Response Code")

        return str(response)
Exemplo n.º 47
0
    def sweep(self, db):
        cur = db.get_cursor()
        db.execute(
            cur,
            "SELECT host,ip FROM updated_time WHERE updated<datetime('now','-7 days')AND origin=?",
            arglist=[self.origin_text])
        update = None
        pairs = {}
        while True:
            row = cur.fetchone()
            if row is None:
                break
            if update is None:
                update = self.get_updater()
            host = row[0]
            ip = ipaddress.ip_address(row[1])
            if host not in pairs:
                pairs[host] = {ip}
            else:
                pairs[host].add(ip)
            update.delete(
                host,
                dns.rdata.from_text(dns.rdataclass.IN,
                                    nsupdate.rr_type(ip.version),
                                    ip.compressed))
        if update is None:
            return
        dns.query.tcp(update, self.nsupdate_server, port=self.nsupdate_port)

        sqls = []
        for host in pairs.keys():
            ans = self.resolve(host)
            for ip in pairs[host]:
                if ans is not None and ip in ans:
                    log.warn(f'removed host is still resolvable: {host}: {ip}')
                    continue
                sqls.append((
                    "DELETE FROM updated_time WHERE host=? AND ip=? AND origin=?",
                    host, ip.compressed, self.origin_text))
                log.warn(f'deleting unseen {host}: {ip}')

        for sql in sqls:
            db.execute(cur, sql[0], arglist=sql[1:], commit=False)
        db.commit()
        db.vacuum()
Exemplo n.º 48
0
Arquivo: ddns.py Projeto: jgrip/ddns
def update():
    if 'hostname' not in request.args:
        abort(400)
    if 'myip' not in request.args:
        abort(400)
    hostname = dns.name.from_text(request.args['hostname'])
    domain = dns.name.from_text(DOMAIN)
    particle = hostname.relativize(domain)
    if not hostname.is_subdomain(domain):
        return 'nohost'
    update = dns.update.Update(DOMAIN, keyring=KEYRING)
    update.delete(str(particle))
    update.add(str(particle), 600, 'a', str(request.args['myip']))
    response = dns.query.tcp(update, DNSHOST)
    if response.rcode() == 0:
        return "good "+str(request.args['myip'])
    else:
        return "dnserr"
Exemplo n.º 49
0
def generate_update_from_diff(zonename, added, removed, oldsoa, keyring,
                              keyalgo, force_conflicts):

    update = dns.update.Update(zonename, keyring=keyring, keyalgorithm=keyalgo)

    if (not force_conflicts):
        # Require the old SOA to still be present
        # (Essentially requires that the zone hasn't changed while editing)

        update.present(oldsoa[0], oldsoa[2])

    for (name, ttl, rdata) in removed:
        update.delete(name, rdata)

    for (name, ttl, rdata) in added:
        update.add(name, ttl, rdata)

    return update
Exemplo n.º 50
0
def delete_record(record, server, key_file, key_name):
    if determine_if_ip_address(record):
        reverse_record = str(dns.reversename.from_address(record))
        re_record = re.search(r"([0-9]+)\.(.*).$", reverse_record)
    else:
        re_record = re.search(r"(\w+)\.(.*)$", record)

    record = re_record.group(1)
    domain = re_record.group(2)

    try:
        key_ring = keyutils.read_tsigkey(key_file, key_name)
    except:
        raise

    update = dns.update.Update(domain, keyring = key_ring)
    update.delete(record)
    response = dns.query.tcp(update, server)
    print "Record Deletion Output: %s\n" % response
Exemplo n.º 51
0
def generate_update_from_diff(zonename, original_zone, updated_zone,
                              keyring, keyalgo, force_conflicts):
    update = dns.update.Update(zonename, keyring = keyring,
                               keyalgorithm = keyalgo)

    if (not force_conflicts):
        # Require the old SOA to still be present
        # (Essentially requires that the zone hasn't changed while editing)
        oldsoa = get_single_record(original_zone.iterate_rdatas(), 
                                   dns.rdatatype.SOA)
        update.present(oldsoa[0], oldsoa[2])

    added, removed = get_zone_diff(original_zone, updated_zone)

    for (name, ttl, rdata) in removed:
        update.delete(name, rdata)

    for (name, ttl, rdata) in added:
        update.add(name, ttl, rdata)

    return [update, len(added), len(removed)]
Exemplo n.º 52
0
    def configure(self):
        cfg = self.ud.getSection('dnsupdate')
        for key in ('tsighost', 'tsigkey', 'host', 'domain', 'server'):
            if key not in cfg:
                return

        instanceid = self.id.getInstanceId()
        ipaddr = self.id.getPublicIPv4()

        template = True
        for key in ('prefix', 'domain', 'start'):
            if key not in cfg:
                template = False
                break

        if template:
            index = int(self.id.getAMILaunchIndex())
            start = int(cfg['start'])
            clusterid = '%02d' % (start + index)
            cfg['host'] = '%s%s' % (cfg['prefix'], clusterid)

        # Set keyring using TSIG variables from User Data
        keyring = dns.tsigkeyring.from_text({
            cfg['tsighost'] : cfg['tsigkey']
        })
        update = dns.update.Update(cfg['domain'], keyring=keyring)

        # Clear all TXT and A entries for domain
        update.delete(cfg['host'], 'a')
        dns.query.tcp(update, cfg['server'])
        update.delete(cfg['host'], 'txt')
        dns.query.tcp(update, cfg['server'])

        # Create A entry with public IP address
        update.add(cfg['host'], 300, 'a', ipaddr)
        dns.query.tcp(update, cfg['server'])

        # Create TXT entry with instanceID
        update.add(cfg['host'], 300, 'txt', instanceid)
        dns.query.tcp(update, cfg['server'])
Exemplo n.º 53
0
def modify_zone_record(domain_name, domain_ip, key_file):
    """modify DNS zone record from dns server and return rcode.

    Args:
        String domain_name
        String domain_ip

    Returns:
        String rcode
    issue #1: when update the forward record, also need update the reserve record
    issue #2: before update the forward record, u need validate if the record is exist,if not exist, return fail, if exist ,return              success,and update the record
    """
    KeyRing = getKey(key_file)
    ttl = 3600
    record_type = "A"
    domain = dns.name.from_text(DOMAIN)
    update = dns.update.Update(DOMAIN, keyring = KeyRing)
    update.delete(str(domain_name))
    update.add(str(domain_name), ttl, record_type, str(domain_ip))
    response = dns.query.tcp(update, DNSHOST)
    rcode = response.rcode()
    return rcode
Exemplo n.º 54
0
    def deletedns_records(self):
        config = getconfig.Config()
        dbcon = dbconn.DbConn()
        configParser = config.getConfig()
        keyname = configParser['keyname']
        secretkey = configParser['secretkey']
        zone = configParser['zone']
        dnsServer = configParser['dnsserver']
        ddnsRecords = dbcon.getRecords()
        self.LOG.debug("zone: {}, dnsserver: {}".format(zone, dnsServer))
        for row in ddnsRecords:
            '''rd.created_at, rd.updated_at, rd.data, rs.name, rs.type, rs.ttl'''
            vmname = row[4][:len(row[4])-(len(zone)+1)]
            ip = row[2]
            recType = row[5]
            created = row[0]
            updated = row[1]
            action = row[3]
            if action == 'DELETE':
                try:
                    keyring = dns.tsigkeyring.from_text({keyname : secretkey})
                except:
                    raise
                update = dns.update.Update(zone, keyring=keyring)
                self.LOG.debug("vmname: {}, recordType: {}".format(vmname, recType))
                update.delete(vmname, recType)

                try:
                    response = dns.query.tcp(update, dnsServer)
                except dns.tsig.PeerBadKey:
                    self.LOG.exception("The remote DNS server ns5.kcdc.att.com. did not accept the key passed.")
                    raise
                except Exception, err:
                    exc_type, exc_obj, exc_tb = sys.exc_info()
                    self.LOG.exception("type: %s, obj: %s, tb: %s" % (exc_type, exc_obj, exc_tb))
                    self.LOG.exception("Unhandled exception in add_forward_record: %s" % err)
                    raise
                self.LOG.debug("Forward Record Output: %s" % response)
Exemplo n.º 55
0
    def remove_record(self):
        result = {'changed': False, 'failed': False}

        if self.record_exists() == 0:
            return result

        # Check mode and record exists, declared fake change.
        if self.module.check_mode:
            self.module.exit_json(changed=True)

        update = dns.update.Update(self.zone, keyring=self.keyring, keyalgorithm=self.algorithm)
        update.delete(self.module.params['record'], self.module.params['type'])

        response = self.__do_update(update)
        self.dns_rc = dns.message.Message.rcode(response)

        if self.dns_rc != 0:
            result['failed'] = True
            result['msg'] = "Failed to delete record (rc: %d)" % self.dns_rc
        else:
            result['changed'] = True

        return result
Exemplo n.º 56
0
 def test_to_wire1(self): # type: () -> None
     update = dns.update.Update('example')
     update.id = 1
     update.present('foo')
     update.present('foo', 'a')
     update.present('bar', 'a', '10.0.0.5')
     update.absent('blaz2')
     update.absent('blaz2', 'a')
     update.replace('foo', 300, 'a', '10.0.0.1', '10.0.0.2')
     update.add('bar', 300, 'a', '10.0.0.3')
     update.delete('bar', 'a', '10.0.0.4')
     update.delete('blaz', 'a')
     update.delete('blaz2')
     self.failUnless(update.to_wire() == goodwire)
Exemplo n.º 57
0
 def test_to_wire3(self):
     update = dns.update.Update('example')
     update.id = 1
     update.present('foo')
     update.present('foo', 'a')
     update.present('bar', 'a', '10.0.0.5')
     update.absent('blaz2')
     update.absent('blaz2', 'a')
     update.replace('foo', 300, 'a', '10.0.0.1', '10.0.0.2')
     update.add('bar', dns.rdataset.from_text(1, 1, 300, '10.0.0.3'))
     update.delete('bar', 'a', '10.0.0.4')
     update.delete('blaz', 'a')
     update.delete('blaz2')
     self.failUnless(update.to_wire() == goodwire)
Exemplo n.º 58
0
if __name__ == '__main__':
    options, args = parse_options()

    print options.remove, options.add
    if not (options.remove or options.add):
        print "figure out how to print usage"
        sys.exit(1)
 
    config = load_config(options.config)

    tsig =  config['domain']['tsig']
    domain_name = config['domain']['name']
    name_server = config['domain']['server']
    ttl = config['domain']['ttl']

    keyring = dns.tsigkeyring.from_text({
        "%s." % (domain_name) : tsig
    })
    
    update = dns.update.Update(domain_name, keyring=keyring)

    if options.remove:
        update.delete(options.name, 'A', options.ipaddress)
    elif options.add:
        update.add(options.name, ttl, 'A', options.ipaddress)
    try:
        response = dns.query.tcp(update, name_server)
    except Exception, e:
        print e