Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# Authors: # Martin Kosek <mkosek@redhat.com> # Pavel Zuna <pzuna@redhat.com> # # Copyright (C) 2010 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>.
validate_hostname, validate_dns_label, validate_domain_name, get_dns_forward_zone_update_policy, get_dns_reverse_zone_update_policy, get_reverse_zone_default, zone_is_reverse, REVERSE_DNS_ZONES)
Domain Name System (DNS)
Manage DNS zone and resource records.
USING STRUCTURED PER-TYPE OPTIONS
There are many structured DNS RR types where DNS data stored in LDAP server is not just a scalar value, for example an IP address or a domain name, but a data structure which may be often complex. A good example is a LOC record [RFC1876] which consists of many mandatory and optional parts (degrees, minutes, seconds of latitude and longitude, altitude or precision).
It may be difficult to manipulate such DNS records without making a mistake and entering an invalid value. DNS module provides an abstraction over these raw records and allows to manipulate each RR type with specific options. For each supported RR type, DNS module provides a standard option to manipulate a raw records with format --<rrtype>-rec, e.g. --mx-rec, and special options for every part of the RR structure with format --<rrtype>-<partname>, e.g. --mx-preference and --mx-exchanger.
When adding a record, either RR specific options or standard option for a raw value can be used, they just should not be combined in one add operation. When modifying an existing entry, new RR specific options can be used to change one part of a DNS record, where the standard option for raw value is used to specify the modified value. The following example demonstrates a modification of MX record preference from 0 to 1 in a record without modifying the exchanger: ipa dnsrecord-mod --mx-rec="0 mx.example.com." --mx-preference=1
EXAMPLES:
Add new zone: ipa dnszone-add example.com --name-server=nameserver.example.com \\ --admin-email=admin@example.com
Add system permission that can be used for per-zone privilege delegation: ipa dnszone-add-permission example.com
Modify the zone to allow dynamic updates for hosts own records in realm EXAMPLE.COM: ipa dnszone-mod example.com --dynamic-update=TRUE
This is the equivalent of: ipa dnszone-mod example.com --dynamic-update=TRUE \\ --update-policy="grant EXAMPLE.COM krb5-self * A; grant EXAMPLE.COM krb5-self * AAAA; grant EXAMPLE.COM krb5-self * SSHFP;"
Modify the zone to allow zone transfers for local network only: ipa dnszone-mod example.com --allow-transfer=10.0.0.0/8
Add new reverse zone specified by network IP address: ipa dnszone-add --name-from-ip=80.142.15.0/24 \\ --name-server=nameserver.example.com
Add second nameserver for example.com: ipa dnsrecord-add example.com @ --ns-rec=nameserver2.example.com
Add a mail server for example.com: ipa dnsrecord-add example.com @ --mx-rec="10 mail1"
Add another record using MX record specific options: ipa dnsrecord-add example.com @ --mx-preference=20 --mx-exchanger=mail2
Add another record using interactive mode (started when dnsrecord-add, dnsrecord-mod, or dnsrecord-del are executed with no options): ipa dnsrecord-add example.com @ Please choose a type of DNS resource record to be added The most common types for this type of zone are: NS, MX, LOC
DNS resource record type: MX MX Preference: 30 MX Exchanger: mail3 Record name: example.com MX record: 10 mail1, 20 mail2, 30 mail3 NS record: nameserver.example.com., nameserver2.example.com.
Delete previously added nameserver from example.com: ipa dnsrecord-del example.com @ --ns-rec=nameserver2.example.com.
Add LOC record for example.com: ipa dnsrecord-add example.com @ --loc-rec="49 11 42.4 N 16 36 29.6 E 227.64m"
Add new A record for www.example.com. Create a reverse record in appropriate reverse zone as well. In this case a PTR record "2" pointing to www.example.com will be created in zone 15.142.80.in-addr.arpa. ipa dnsrecord-add example.com www --a-rec=80.142.15.2 --a-create-reverse
Add new PTR record for www.example.com ipa dnsrecord-add 15.142.80.in-addr.arpa. 2 --ptr-rec=www.example.com.
Add new SRV records for LDAP servers. Three quarters of the requests should go to fast.example.com, one quarter to slow.example.com. If neither is available, switch to backup.example.com. ipa dnsrecord-add example.com _ldap._tcp --srv-rec="0 3 389 fast.example.com" ipa dnsrecord-add example.com _ldap._tcp --srv-rec="0 1 389 slow.example.com" ipa dnsrecord-add example.com _ldap._tcp --srv-rec="1 1 389 backup.example.com"
The interactive mode can be used for easy modification: ipa dnsrecord-mod example.com _ldap._tcp No option to modify specific record provided. Current DNS record contents:
SRV record: 0 3 389 fast.example.com, 0 1 389 slow.example.com, 1 1 389 backup.example.com
Modify SRV record '0 3 389 fast.example.com'? Yes/No (default No): Modify SRV record '0 1 389 slow.example.com'? Yes/No (default No): y SRV Priority [0]: (keep the default value) SRV Weight [1]: 2 (modified value) SRV Port [389]: (keep the default value) SRV Target [slow.example.com]: (keep the default value) 1 SRV record skipped. Only one value per DNS record type can be modified at one time. Record name: _ldap._tcp SRV record: 0 3 389 fast.example.com, 1 1 389 backup.example.com, 0 2 389 slow.example.com
After this modification, three fifths of the requests should go to fast.example.com and two fifths to slow.example.com.
An example of the interactive mode for dnsrecord-del command: ipa dnsrecord-del example.com www No option to delete specific record provided. Delete all? Yes/No (default No): (do not delete all records) Current DNS record contents:
A record: 1.2.3.4, 11.22.33.44
Delete A record '1.2.3.4'? Yes/No (default No): Delete A record '11.22.33.44'? Yes/No (default No): y Record name: www A record: 1.2.3.4 (A record 11.22.33.44 has been deleted)
Show zone example.com: ipa dnszone-show example.com
Find zone with "example" in its domain name: ipa dnszone-find example
Find records for resources with "www" in their name in zone example.com: ipa dnsrecord-find example.com www
Find A records with value 10.10.0.1 in zone example.com ipa dnsrecord-find example.com --a-rec=10.10.0.1
Show records for resource www in zone example.com ipa dnsrecord-show example.com www
Forward all requests for the zone external.com to another nameserver using a "first" policy (it will send the queries to the selected forwarder and if not answered it will use global resolvers): ipa dnszone-add external.com ipa dnszone-mod external.com --forwarder=10.20.0.1 \\ --forward-policy=first
Delete zone example.com with all resource records: ipa dnszone-del example.com
Resolve a host name to see if it exists (will add default IPA domain if one is not included): ipa dns-resolve www.example.com ipa dns-resolve www
GLOBAL DNS CONFIGURATION
DNS configuration passed to command line install script is stored in a local configuration file on each IPA server where DNS service is configured. These local settings can be overridden with a common configuration stored in LDAP server:
Show global DNS configuration: ipa dnsconfig-show
Modify global DNS configuration and set a list of global forwarders: ipa dnsconfig-mod --forwarder=10.0.0.1 """)
# supported resource record types u'A', u'AAAA', u'A6', u'AFSDB', u'APL', u'CERT', u'CNAME', u'DHCID', u'DLV', u'DNAME', u'DNSKEY', u'DS', u'HIP', u'IPSECKEY', u'KEY', u'KX', u'LOC', u'MX', u'NAPTR', u'NS', u'NSEC', u'NSEC3', u'NSEC3PARAM', u'PTR', u'RRSIG', u'RP', u'SIG', u'SPF', u'SRV', u'SSHFP', u'TA', u'TKEY', u'TSIG', u'TXT', )
# DNS zone record identificator
# most used record types, always ask for those in interactive prompt
# attributes derived from record types
# supported DNS classes, IN = internet, rest is almost never used
except ValueError, e: return unicode(e)
""" Generate serial number for zones. bind-dyndb-ldap expects unix time in to be used for SOA serial.
SOA serial in a date format would also work, but it may be set to far future when many DNS updates are done per day (more than 100). Unix timestamp is more resilient to this issue. """
else: # use more sensible default prefix than netaddr default
elif net.version == 6: return u'.'.join(items[32 - net.prefixlen / 4:]) else: return None
return _('invalid IP address version (is %(value)d, must be %(required_value)d)!') \ % dict(value=ip.version, required_value=ip_version) except (netaddr.AddrFormatError, ValueError): return _('invalid IP address format')
return
return _('each ACL element must be terminated with a semicolon') else:
allow_network=True, allow_loopback=True) except UnboundLocalError: return _(u"invalid address format")
return
allow_network=True, allow_loopback=True) else:
# Allow domain name which is not fully qualified. These are supported # in bind and then translated as <non-fqdn-name>.<domain>. % unicode(e)
value.split(u'.'))
return ip_address_validation
try: port = int(port) if port < 0 or port > 65535: raise ValueError() except ValueError: return _('%(port)s is not a valid port' % dict(port=port))
% unicode(e)
"""Make it fully-qualified""" else:
addr = netaddr.IPAddress(str_address) if addr.version == 4: result = api.Command['dnsrecord_find'](zone, arecord=str_address) elif addr.version == 6: result = api.Command['dnsrecord_find'](zone, aaaarecord=str_address) else: raise ValueError('Invalid address family')
return result['count'] > 0
elif addr.version == 6: api.Command['dnsrecord_add'](zone, name, aaaarecord=str_address) else: raise ValueError('Invalid address family')
else: if ip.version == 4: pos = 4 - prefixlen / 8 elif ip.version == 6: pos = 32 - prefixlen / 4 items = ip.reverse_dns.split('.') revzone = u'.'.join(items[pos:])
try: api.Command['dnszone_show'](revzone) except errors.NotFound: revzone = u''
raise errors.NotFound( reason=_('DNS reverse zone for IP address %(addr)s not found') % dict(addr=ipaddr) )
except errors.NotFound: raise errors.NotFound( reason=_('DNS zone %(zone)s not found') % dict(zone=domain) )
except Exception, e: raise errors.ValidationError(name=option_name, error=unicode(e))
if is_forward_record(domain, unicode(ip)): raise errors.DuplicateEntry( message=_(u'IP address %(ip)s is already assigned in domain %(domain)s.')\ % dict(ip=str(ip), domain=domain))
prefixlen = ip.prefixlen # we prefer lookup of the IP through the reverse zone message=_(u'Reverse record for IP address %(ip)s already exists in reverse zone %(zone)s.')\ % dict(ip=str(ip), zone=revzone)) pass
add_forward_record(domain, host, unicode(ip))
prefixlen = ip.prefixlen except errors.EmptyModlist: # the entry already exists and matches pass
# a list of parts that create the actual raw DNS record # an optional list of parameters used in record-specific operations # supported RR types: https://fedorahosted.org/bind-dyndb-ldap/browser/doc/schema
('validatedns', bool, True), ('normalizedns', bool, True), )
# should be replaced in subclasses
raise ValueError("Unknown RR type: %s. Must be one of %s" % \ (str(self.rrtype), ", ".join(_record_types)))
for v in values if v is not None)
for part in self.parts)
return
cli_name = self.cli_name_format % (self.rrtype.lower(), self.parts[val_id].name) raise errors.ConversionError(name=self.name, error=_("'%s' is a required part of DNS record") % cli_name)
raise errors.ValidationError(name=self.name, error=_("Invalid number of parts!"))
self._normalize_parts(v) for v in value \ if v is not None )
""" Normalize a DNS record value using normalizers for its parts. """ return value
if values[part_id] is not None else None for part_id, part in enumerate(self.parts) ]
for part_id, part in enumerate(self.parts) ]
except Exception: # cannot normalize, rather return original value than fail pass
return
return
return
return _('DNS RR type "%s" is not supported by bind-dyndb-ldap plugin') \ % self.rrtype
return
# validate record format
else: see_rfc_msg = "" % dict(format=" ".join(part_names), rfcs=see_rfc_msg) else: return self.format_error_msg
# validate every part
""" All parts of DNSRecord need to be processed and modified before they can be added to global DNS API. For example a prefix need to be added before part name so that the name is unique in the global namespace. """
cli_name=cli_name, label=label, required=False, option_group=option_group, flags=flags, hint=self.name,) # name of parent RR param
""" Parameters for special per-type behavior need to be processed in the same way as record parts in _convert_dnsrecord_part(). """
cli_name=cli_name, label=label, required=False, option_group=option_group, flags=flags, hint=self.name,) # name of parent RR param
optional=optional, default=default) raw = default
except (errors.ValidationError, errors.ConversionError), e: backend.textui.print_prompt_attribute_error( unicode(label), unicode(e.error))
mod_parts = self._get_part_values(mod_dnsvalue)
return user_options
default = mod_parts[part_id] else:
return user_options
continue
# callbacks for per-type special record behavior
Flag('create_reverse?', label=_('Create reverse'), doc=_('Create reverse record for this IP Address'), flags=['no_update'] ), )
# --<rrtype>-create-reverse is set, but there are not records raise errors.RequirementError(name=self.name)
check_forward=False, check_reverse=True)
# make sure we don't run this post callback action again in nested # commands, line adding PTR record in add_records_for_host add_forward=False, add_reverse=True) except Exception, e: raise errors.NonFatalError( reason=_('Cannot create reverse record for "%(value)s": %(exc)s') \ % dict(value=record, exc=unicode(e)))
Str('ip_address', _validate_ip4addr, label=_('IP Address'), ), )
Str('data', label=_('Record data'), ), )
# A6 RR type is obsolete and only a raw interface is provided return (value,)
Str('ip_address', _validate_ip6addr, label=_('IP Address'), ), )
Int('subtype?', label=_('Subtype'), minvalue=0, maxvalue=65535, ), Str('hostname', _bind_hostname_validator, label=_('Hostname'), ), )
Int('type', label=_('Certificate Type'), minvalue=0, maxvalue=65535, ), Int('key_tag', label=_('Key Tag'), minvalue=0, maxvalue=65535, ), Int('algorithm', label=_('Algorithm'), minvalue=0, maxvalue=255, ), Str('certificate_or_crl', label=_('Certificate/CRL'), ), )
Str('hostname', _bind_hostname_validator, label=_('Hostname'), doc=_('A hostname which this alias hostname points to'), ), )
Str('target', _bind_hostname_validator, label=_('Target'), ), )
Int('key_tag', label=_('Key Tag'), minvalue=0, maxvalue=65535, ), Int('algorithm', label=_('Algorithm'), minvalue=0, maxvalue=255, ), Int('digest_type', label=_('Digest Type'), minvalue=0, maxvalue=255, ), Str('digest', label=_('Digest'), ), )
Int('flags', label=_('Flags'), minvalue=0, maxvalue=65535, ), Int('protocol', label=_('Protocol'), minvalue=0, maxvalue=255, ), Int('algorithm', label=_('Algorithm'), minvalue=0, maxvalue=255, ), Str('public_key', label=_('Public Key'), ), )
Int('preference', label=_('Preference'), doc=_('Preference given to this exchanger. Lower values are more preferred'), minvalue=0, maxvalue=65535, ), Str('exchanger', _bind_hostname_validator, label=_('Exchanger'), doc=_('A host willing to act as a key exchanger'), ), )
Int('lat_deg', label=_('Degrees Latitude'), minvalue=0, maxvalue=90, ), Int('lat_min?', label=_('Minutes Latitude'), minvalue=0, maxvalue=59, ), Decimal('lat_sec?', label=_('Seconds Latitude'), minvalue='0.0', maxvalue='59.999', precision=3, ), StrEnum('lat_dir', label=_('Direction Latitude'), values=(u'N', u'S',), ), Int('lon_deg', label=_('Degrees Longitude'), minvalue=0, maxvalue=180, ), Int('lon_min?', label=_('Minutes Longitude'), minvalue=0, maxvalue=59, ), Decimal('lon_sec?', label=_('Seconds Longitude'), minvalue='0.0', maxvalue='59.999', precision=3, ), StrEnum('lon_dir', label=_('Direction Longitude'), values=(u'E', u'W',), ), Decimal('altitude', label=_('Altitude'), minvalue='-100000.00', maxvalue='42849672.95', precision=2, ), Decimal('size?', label=_('Size'), minvalue='0.0', maxvalue='90000000.00', precision=2, ), Decimal('h_precision?', label=_('Horizontal Precision'), minvalue='0.0', maxvalue='90000000.00', precision=2, ), Decimal('v_precision?', label=_('Vertical Precision'), minvalue='0.0', maxvalue='90000000.00', precision=2, ), )
"d1 [m1 [s1]] {"N"|"S"} d2 [m2 [s2]] {"E"|"W"} alt["m"] [siz["m"] [hp["m"] [vp["m"]]]]" where: d1: [0 .. 90] (degrees latitude) d2: [0 .. 180] (degrees longitude) m1, m2: [0 .. 59] (minutes latitude/longitude) s1, s2: [0 .. 59.999] (seconds latitude/longitude) alt: [-100000.00 .. 42849672.95] BY .01 (altitude in meters) siz, hp, vp: [0 .. 90000000.00] (size/precision in meters) See RFC 1876 for details""")
r'(?P<d1>\d{1,2}\s+)(?P<m1>\d{1,2}\s+)?(?P<s1>\d{1,2}\.?\d{1,3}?\s+)?'\ r'(?P<dir1>[N|S])\s+'\ r'(?P<d2>\d{1,3}\s+)(?P<m2>\d{1,2}\s+)?(?P<s2>\d{1,2}\.?\d{1,3}?\s+)?'\ r'(?P<dir2>[W|E])\s+'\ r'(?P<alt>-?\d{1,8}\.?\d{1,2}?)m?\s*'\ r'(?P<siz>\d{1,8}\.?\d{1,2}?)?m?\s*'\ r'(?P<hp>\d{1,8}\.?\d{1,2}?)?m?\s*(?P<vp>\d{1,8}\.?\d{1,2}?)?m?\s*$')
return None
# create part_name -> part_id map first for part_id,part in enumerate(self.parts))
('lon_sec', 'lon_min'), ('h_precision', 'size'), ('v_precision', 'h_precision', 'size') )
target_cli_name = self.cli_name_format % (self.rrtype.lower(), req[0]) required_cli_names = [ self.cli_name_format % (self.rrtype.lower(), part) for part in req[1:] ] error = _("'%(required)s' must not be empty when '%(name)s' is set") % \ dict(required=', '.join(required_cli_names), name=target_cli_name) raise errors.ValidationError(name=self.name, error=error)
Int('preference', label=_('Preference'), doc=_('Preference given to this exchanger. Lower values are more preferred'), minvalue=0, maxvalue=65535, ), Str('exchanger', _bind_hostname_validator, label=_('Exchanger'), doc=_('A host willing to act as a mail exchanger'), ), )
Str('hostname', _bind_hostname_validator, label=_('Hostname'), ), )
'[TYPE2 [TYPE3 [...]]]" (see RFC 4034 for details)')
Str('next', _bind_hostname_validator, label=_('Next Domain Name'), ), StrEnum('types+', label=_('Type Map'), values=_allowed_types, csv=True, ), )
values = value.split()
if len(values) < 2: return None
return (values[0], tuple(values[1:]))
types = [types,] for v in values_flat if v is not None)
allowed_flags = u'SAUP' flags = flags.replace('"','').replace('\'','')
for flag in flags: if flag not in allowed_flags: return _('flags must be one of "S", "A", "U", or "P"')
Int('order', label=_('Order'), minvalue=0, maxvalue=65535, ), Int('preference', label=_('Preference'), minvalue=0, maxvalue=65535, ), Str('flags', _validate_naptr_flags, label=_('Flags'), normalizer=lambda x:x.upper() ), Str('service', label=_('Service'), ), Str('regexp', label=_('Regular Expression'), ), Str('replacement', label=_('Replacement'), ), )
Str('hostname', _hostname_validator, normalizer=_normalize_hostname, label=_('Hostname'), doc=_('The hostname this reverse record points to'), ), )
# service not available return
Int('priority', label=_('Priority'), minvalue=0, maxvalue=65535, ), Int('weight', label=_('Weight'), minvalue=0, maxvalue=65535, ), Int('port', label=_('Port'), minvalue=0, maxvalue=65535, ), Str('target', _srv_target_validator, label=_('Target'), doc=_('The domain name of the target host or \'.\' if the service is decidedly not available at this domain'), ), )
time_format = "%Y%m%d%H%M%S" try: time.strptime(value, time_format) except ValueError: return _('the value does not follow "YYYYMMDDHHMMSS" time format')
StrEnum('type_covered', label=_('Type Covered'), values=_allowed_types, ), Int('algorithm', label=_('Algorithm'), minvalue=0, maxvalue=255, ), Int('labels', label=_('Labels'), minvalue=0, maxvalue=255, ), Int('original_ttl', label=_('Original TTL'), minvalue=0, ), Str('signature_expiration', _sig_time_validator, label=_('Signature Expiration'), ), Str('signature_inception', _sig_time_validator, label=_('Signature Inception'), ), Int('key_tag', label=_('Key Tag'), minvalue=0, maxvalue=65535, ), Str('signers_name', label=_('Signer\'s Name'), ), Str('signature', label=_('Signature'), ), )
Int('algorithm', label=_('Algorithm'), minvalue=0, maxvalue=255, ), Int('fp_type', label=_('Fingerprint Type'), minvalue=0, maxvalue=255, ), Str('fingerprint', label=_('Fingerprint'), ), )
Str('data', label=_('Text Data'), ), )
# ignore any space in TXT record
ARecord(), AAAARecord(), A6Record(), AFSDBRecord(), APLRecord(), CERTRecord(), CNAMERecord(), DHCIDRecord(), DLVRecord(), DNAMERecord(), DNSKEYRecord(), DSRecord(), HIPRecord(), IPSECKEYRecord(), KEYRecord(), KXRecord(), LOCRecord(), MXRecord(), NAPTRRecord(), NSRecord(), NSECRecord(), NSEC3Record(), NSEC3PARAMRecord(), PTRRecord(), RRSIGRecord(), RPRecord(), SIGRecord(), SPFRecord(), SRVRecord(), SSHFPRecord(), TARecord(), TKEYRecord(), TSIGRecord(), TXTRecord(), )
label=_('Records'), flags=['no_create', 'no_search', 'no_update'],), Str('dnstype?', label=_('Record type'), flags=['no_create', 'no_search', 'no_update'],), Str('dnsdata?', label=_('Record data'), flags=['no_create', 'no_search', 'no_update'],)): # These 3 options are used in --structured format. They are defined # rather in takes_params than has_output_params because of their # order - they should be printed to CLI before any DNS part param
if record.supported)
# this is a DNS name relative to the zone reason=_('Nameserver \'%(host)s\' does not have a corresponding A/AAAA record') % {'host': name} )
except errors.NotFound: return False
else:
Str('managedby', label=_('Managedby permission'), ), )
""" DNS Zone, container for resource records. """ 'idnsname', 'idnszoneactive', 'idnssoamname', 'idnssoarname', 'idnssoaserial', 'idnssoarefresh', 'idnssoaretry', 'idnssoaexpire', 'idnssoaminimum', 'idnsallowquery', 'idnsallowtransfer', 'idnsforwarders', 'idnsforwardpolicy' ] + _record_attributes
Str('idnsname', _domain_name_validator, cli_name='name', label=_('Zone name'), doc=_('Zone name (FQDN)'), default_from=lambda name_from_ip: _reverse_zone_name(name_from_ip), normalizer=lambda value: value.lower(), primary_key=True, ), Str('name_from_ip?', _validate_ipnet, label=_('Reverse zone IP network'), doc=_('IP network to create reverse zone name from'), flags=('virtual_attribute',), ), Str('idnssoamname', cli_name='name_server', label=_('Authoritative nameserver'), doc=_('Authoritative nameserver domain name'), ), Str('idnssoarname', _rname_validator, cli_name='admin_email', label=_('Administrator e-mail address'), doc=_('Administrator e-mail address'), default_from=lambda idnsname: 'hostmaster.%s' % idnsname, normalizer=normalize_zonemgr, ), Int('idnssoaserial', cli_name='serial', label=_('SOA serial'), doc=_('SOA record serial number'), minvalue=1, maxvalue=4294967295L, default_from=_create_zone_serial, autofill=True, ), Int('idnssoarefresh', cli_name='refresh', label=_('SOA refresh'), doc=_('SOA record refresh time'), minvalue=0, maxvalue=2147483647, default=3600, autofill=True, ), Int('idnssoaretry', cli_name='retry', label=_('SOA retry'), doc=_('SOA record retry time'), minvalue=0, maxvalue=2147483647, default=900, autofill=True, ), Int('idnssoaexpire', cli_name='expire', label=_('SOA expire'), doc=_('SOA record expire time'), default=1209600, minvalue=0, maxvalue=2147483647, autofill=True, ), Int('idnssoaminimum', cli_name='minimum', label=_('SOA minimum'), doc=_('How long should negative responses be cached'), default=3600, minvalue=0, maxvalue=2147483647, autofill=True, ), Int('dnsttl?', cli_name='ttl', label=_('SOA time to live'), doc=_('SOA record time to live'), minvalue=0, maxvalue=2147483647, # see RFC 2181 ), StrEnum('dnsclass?', cli_name='class', label=_('SOA class'), doc=_('SOA record class'), values=_record_classes, ), Str('idnsupdatepolicy?', cli_name='update_policy', label=_('BIND update policy'), doc=_('BIND update policy'), default_from=lambda idnsname: default_zone_update_policy(idnsname), autofill=True ), Bool('idnszoneactive?', cli_name='zone_active', label=_('Active zone'), doc=_('Is zone active?'), flags=['no_create', 'no_update'], attribute=True, ), Bool('idnsallowdynupdate?', cli_name='dynamic_update', label=_('Dynamic update'), doc=_('Allow dynamic updates.'), attribute=True, default=False, autofill=True ), Str('idnsallowquery?', _validate_bind_aci, normalizer=_normalize_bind_aci, cli_name='allow_query', label=_('Allow query'), doc=_('Semicolon separated list of IP addresses or networks which are allowed to issue queries'), default=u'any;', # anyone can issue queries by default autofill=True, ), Str('idnsallowtransfer?', _validate_bind_aci, normalizer=_normalize_bind_aci, cli_name='allow_transfer', label=_('Allow transfer'), doc=_('Semicolon separated list of IP addresses or networks which are allowed to transfer the zone'), default=u'none;', # no one can issue queries by default autofill=True, ), Str('idnsforwarders*', _validate_bind_forwarder, cli_name='forwarder', label=_('Zone forwarders'), doc=_('A list of per-zone forwarders. A custom port can be specified ' 'for each forwarder using a standard format "IP_ADDRESS port PORT"'), csv=True, ), StrEnum('idnsforwardpolicy?', cli_name='forward_policy', label=_('Forward policy'), values=(u'only', u'first',), ), Bool('idnsallowsyncptr?', cli_name='allow_sync_ptr', label=_('Allow PTR sync'), doc=_('Allow synchronization of forward (A, AAAA) and reverse (PTR) records in the zone'), ), )
else:
Flag('force', label=_('Force'), doc=_('Force DNS zone creation even if nameserver not in DNS.'), ), Str('ip_address?', _validate_ipaddr, doc=_('Add the nameserver to DNS with this IP address'), ), )
raise errors.NotFound(reason=_('DNS is not configured'))
# Check nameserver has a forward record
# NS record must contain domain name raise errors.ValidationError(name='name-server', error=unicode(_("Nameserver address is not a fully qualified domain name")))
nsparts[0], options['ip_address'])
force=True)
# FIXME: Check that name_from_ip is valid. This is necessary because # custom validation rules, including _validate_ipnet, are not # used when doing a search. Once we have a parameter type for # IP network objects, this will no longer be necessary, as the # parameter type will handle the validation itself (see # <https://fedorahosted.org/freeipa/ticket/2266>). self.obj.params['name_from_ip'](unicode(options['name_from_ip']))
if 'idnsname' not in options: options['idnsname'] = self.obj.params['idnsname'].get_default(**options) del options['name_from_ip']
Flag('forward_only', label=_('Forward zones only'), cli_name='forward_only', doc=_('Search for forward zones only'), ), )
trailing_wildcard=False)
except errors.EmptyModlist: pass
except errors.EmptyModlist: pass
permissiontype=u'SYSTEM' )['result']
result=True, value=permission_name, )
except errors.EmptyModlist: # managedBy attribute is clean, lets make sure there is also no # dangling DNS zone permission pass
result=True, value=permission_name, )
""" DNS record. """
Str('idnsname', _dns_record_name_validator, cli_name='name', label=_('Record name'), doc=_('Record name'), primary_key=True, ), Int('dnsttl?', cli_name='ttl', label=_('Time to live'), doc=_('Time to live'), ), StrEnum('dnsclass?', cli_name='class', label=_('Class'), doc=_('DNS class'), values=_record_classes, ), ) + _dns_record_options
label=_('Structured'), doc=_('Parse all raw DNS records and return them in a structured way'), )
return addr = u'' else:
allowed_zones = ', '.join(REVERSE_DNS_ZONES) raise errors.ValidationError(name='ptrrecord', error=unicode(_('Reverse zone for PTR record should be a sub-zone of one the following fully qualified domains: %s') % allowed_zones))
raise errors.ValidationError(name='ptrrecord', error=unicode(_('Reverse zone %(name)s requires exactly %(count)d IP address components, %(user_count)d given') % dict(name=zone_name, count=zone_len, user_count=ip_addr_comp_count)))
# zone must exist except errors.NotFound: self.api.Object['dnszone'].handle_not_found(keys[-2])
try: cliname = attr[:-len('record')].upper() except IndexError: cliname = attr return cliname
ldap = self.api.Backend.ldap2 base_dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), self.api.env.basedn) ldap_filter = '(&(objectClass=ipaConfigObject)(cn=DNS))' dns_masters = []
try: entries = ldap.find_entries(filter=ldap_filter, base_dn=base_dn)[0]
for entry in entries: master_dn = entry[0] assert isinstance(master_dn, DN) try: master = master_dn[1]['cn'] dns_masters.append(master) except (IndexError, KeyError): pass except errors.NotFound: return []
return dns_masters
if attr in self.params and not self.params[attr].primary_key)
for attr in record.keys(): try: param = self.params[attr] except KeyError: continue
if not isinstance(param, DNSRecord): continue parts_params = param.get_parts()
for dnsvalue in record[attr]: dnsentry = { u'dnstype' : unicode(param.rrtype), u'dnsdata' : dnsvalue } values = param._get_part_values(dnsvalue) if values is None: continue for val_id, val in enumerate(values): if val is not None: dnsentry[parts_params[val_id].name] = val record.setdefault('dnsrecords', []).append(dnsentry) del record[attr]
""" Get an instance of DNSRecord parameter that has part_name as its part. If such parameter is not found, None is returned
:param part_name Part parameter name """
('dnsrecord_part', 'dnsrecord_extra')):
# All DNS record part or extra parameters contain a name of its # parent RR parameter in its hint attribute
""" Iterates through all DNSRecord instances that has at least one of its parts or extra options in given dictionary. It returns the DNSRecord instance only for the first occurence of part/extra option.
:param kw Dictionary with DNS record parts or extra options :param skip_extra Skip DNS record extra options, yield only DNS records with a real record part """
continue
# Test that only allowed combination of record types was created and entry_attrs[attr]) else: # CNAME and PTR record combination is allowed
error=_('CNAME record is not allowed to coexist with any other ' 'records except PTR'))
"Command help may be consulted for all supported record types." Flag('force', label=_('Force'), flags=['no_option', 'no_output'], doc=_('force NS record creation even if its hostname is not in DNS'), ), dnsrecord.structured_flag, )
# Some DNS records were entered, do not use full interactive help # We should still ask user for required parts of DNS parts he is # trying to add in the same way we do for standard LDAP parameters # # Do not ask for required parts when any "extra" option is used, # it can be used to fill all required params by itself prompt_optional=False)
# check zone type common_types = u', '.join(_zone_top_record_types) common_types = u', '.join(_rev_top_record_types) else:
common_types)
return
raise ValueError()
raise ValueError() except (KeyError, ValueError): all_types = u', '.join(_dns_supported_record_types) self.Backend.textui.print_plain(_(u'Invalid or unsupported type. Allowed values are: %s') % all_types) continue
except KeyError: continue
# this record was already entered # this record is entered both via parts and raw records error=_('Raw value of a DNS record was already set by "%(name)s" option') \ % dict(name=rrparam.cli_name or rrparam.name))
# do not run precallback for unset flags # extra option is passed, run per-type pre_callback for given RR type
# Run pre_callback validators
# run precallback also for all new RR type attributes in entry_attrs
# run per-type except KeyError: continue
# Store all new attrs so that DNSRecord post callback is called for # new attributes only and not for all attributes in the LDAP entry
# We always want to retrieve all DNS record attributes to test for # record type collisions (#2601) dn, _record_attributes, normalize=self.obj.normalize_dn) else: entry_attrs[attr] = [] vals = [entry_attrs[attr]] else:
# A new record is being added to existing LDAP DNS object # Update can be safely run as old record values has been # already merged in pre_callback raise exc
dnsrecord.structured_flag, )
# zone rename is not allowed error=_('DNS zone root record cannot be renamed'))
# check if any attr should be updated using structured instead of replaced # format is recordname : (old_value, new_parts)
# old-style modification continue
raise errors.ValidationError(name=param.name, error=_('DNS records can be only updated one at a time'))
# Run pre_callback validators
# current entry is needed in case of per-dns-record-part updates and # for record type collision check normalize=self.obj.normalize_dn)
value=old_dnsvalue)
for part_id,part in enumerate(new_parts))
# remove if empty dn, _record_attributes, normalize=self.obj.normalize_dn)
return self.obj.methods.delentry(*keys)
entry_attrs[self.obj.primary_key.name] = [_dns_zone_record]
try: self.obj.has_cli_options(kw, self.no_option_msg, True) except errors.OptionError: pass else: # some record type entered, skip this helper return
# get DNS record first so that the NotFound exception is raised # before the helper would start dns_record = api.Command['dnsrecord_show'](kw['dnszoneidnsname'], kw['idnsname'])['result'] rec_types = [rec_type for rec_type in dns_record if rec_type in _record_attributes]
self.Backend.textui.print_plain(_("No option to modify specific record provided."))
# ask user for records to be removed self.Backend.textui.print_plain(_(u'Current DNS record contents:\n')) record_params = []
for attr in dns_record: try: param = self.params[attr] except KeyError: continue if not isinstance(param, DNSRecord): continue
record_params.append(param) rec_type_content = u', '.join(dns_record[param.name]) self.Backend.textui.print_plain(u'%s: %s' % (param.label, rec_type_content)) self.Backend.textui.print_plain(u'')
# ask what records to remove for param in record_params: rec_values = list(dns_record[param.name]) for rec_value in dns_record[param.name]: rec_values.remove(rec_value) mod_value = self.Backend.textui.prompt_yesno( _("Modify %(name)s '%(value)s'?") % dict(name=param.label, value=rec_value), default=False) if mod_value is True: user_options = param.prompt_parts(self.Backend, mod_dnsvalue=rec_value) kw[param.name] = [rec_value] kw.update(user_options)
if rec_values: self.Backend.textui.print_plain(ngettext( u'%(count)d %(type)s record skipped. Only one value per DNS record type can be modified at one time.', u'%(count)d %(type)s records skipped. Only one value per DNS record type can be modified at one time.', 0) % dict(count=len(rec_values), type=param.rrtype)) break
""" Delete DNS record entry. """
"Command help may be consulted for all supported record types.")
Flag('del_all', default=False, label=_('Delete all associated records'), ), dnsrecord.structured_flag, )
('dnsrecord_part', 'dnsrecord_extra',)): # options only valid for dnsrecord-mod
dn, _record_attributes, normalize=self.obj.normalize_dn) except errors.NotFound: self.obj.handle_not_found(*keys)
continue vals = [entry_attrs[attr]] else:
except (KeyError, ValueError): try: param = self.params[attr] attr_name = unicode(param.label or param.name) except: attr_name = attr raise errors.AttrValueNotFound(attr=attr_name, value=val)
# set del_all flag in context # when the flag is enabled, the entire DNS record object is deleted # in a post callback
name='del_all', error=_('Zone record \'%s\' cannot be deleted') \ % _dns_zone_record )
self.obj.is_pkey_zone_record(*keys): return self.obj.methods.delentry(*keys)
entry_attrs[self.obj.primary_key.name] = [_dns_zone_record]
return else: # some record type entered, skip this helper return
# get DNS record first so that the NotFound exception is raised # before the helper would start
# ask user for records to be removed
# ask what records to remove _("Delete %(name)s '%(value)s'?") \ % dict(name=param.label, value=rec_value), default=False)
dnsrecord.structured_flag, )
entry_attrs[self.obj.primary_key.name] = [_dns_zone_record]
dnsrecord.structured_flag, )
('dnsrecord_part', 'dnsrecord_extra',)):
# include zone record (root entry) in the search
Str('hostname', label=_('Hostname'), ), )
query = '%s.%s.' % (query, api.env.domain) query = query + '.'
reason=_('Host \'%(host)s\' not found') % {'host': query} )
return dict(result=True, value=query)
""" Checks if any of the servers has the DNS service enabled. """
ldap = self.api.Backend.ldap2 dns_enabled = False
try: ent = ldap.find_entries(filter=self.filter, base_dn=self.base_dn) if len(ent): dns_enabled = True except Exception, e: pass
return dict(result=dns_enabled, value=u'')
""" DNS global configuration object """ 'idnsforwardpolicy', 'idnsforwarders', 'idnsallowsyncptr', 'idnszonerefresh' ]
Str('idnsforwarders*', _validate_bind_forwarder, cli_name='forwarder', label=_('Global forwarders'), doc=_('A list of global forwarders. A custom port can be specified ' \ 'for each forwarder using a standard format "IP_ADDRESS port PORT"'), csv=True, ), StrEnum('idnsforwardpolicy?', cli_name='forward_policy', label=_('Forward policy'), values=(u'only', u'first',), ), Bool('idnsallowsyncptr?', cli_name='allow_sync_ptr', label=_('Allow PTR sync'), doc=_('Allow synchronization of forward (A, AAAA) and reverse (PTR) records'), ), Int('idnszonerefresh?', cli_name='zone_refresh', label=_('Zone refresh interval'), doc=_('An interval between regular polls of the name server for new DNS zones'), minvalue=0, ), )
(dn, entry) = ldap.get_entry(self.get_dn(), None, normalize=self.normalize_dn)
return entry
result = super(dnsconfig_show, self).execute(*keys, **options) self.obj.postprocess_result(result) return result
|