/usr/share/pyshared/provisioningserver/dns/config.py is in python-maas-provisioningserver 1.2+bzr1373+dfsg-0ubuntu1~12.04.6.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | # Copyright 2012 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""DNS configuration."""
from __future__ import (
absolute_import,
print_function,
unicode_literals,
)
__metaclass__ = type
__all__ = [
'DNSConfig',
'DNSForwardZoneConfig',
'DNSReverseZoneConfig',
'setup_rndc',
]
from abc import (
ABCMeta,
abstractproperty,
)
from datetime import datetime
import errno
from itertools import (
chain,
imap,
islice,
)
import os.path
from subprocess import (
check_call,
check_output,
)
from celery.conf import conf
from provisioningserver.dns.utils import generated_hostname
from provisioningserver.utils import (
atomic_write,
incremental_write,
)
import tempita
MAAS_NAMED_CONF_NAME = 'named.conf.maas'
MAAS_NAMED_RNDC_CONF_NAME = 'named.conf.rndc.maas'
MAAS_RNDC_CONF_NAME = 'rndc.conf.maas'
class DNSConfigDirectoryMissing(Exception):
"""The directory where the config was about to be written is missing."""
class DNSConfigFail(Exception):
"""Raised if there's a problem with a DNS config."""
# Default 'controls' statement included in the configuration so that the
# default RNDC can be used (by init scripts).
DEFAULT_CONTROLS = """
controls {
inet 127.0.0.1 port 953 allow { localhost; };
};
"""
def generate_rndc(port=953, key_name='rndc-maas-key',
include_default_controls=True):
"""Use `rndc-confgen` (from bind9utils) to generate a rndc+named
configuration.
`rndc-confgen` generates the rndc configuration which also contains (that
part is commented out) the named configuration.
"""
# Generate the configuration:
# - 256 bits is the recommended size for the key nowadays.
# - Use urandom to avoid blocking on the random generator.
rndc_content = check_output(
['rndc-confgen', '-b', '256', '-r', '/dev/urandom',
'-k', key_name, '-p', str(port)])
# Extract from the result the part which corresponds to the named
# configuration.
start_marker = (
"# Use with the following in named.conf, adjusting the "
"allow list as needed:")
end_marker = '# End of named.conf'
named_start = rndc_content.index(start_marker) + len(start_marker)
named_end = rndc_content.index(end_marker)
named_conf = rndc_content[named_start:named_end].replace('\n# ', '\n')
if include_default_controls:
named_conf += DEFAULT_CONTROLS
# Return a tuple of the two configurations.
return rndc_content, named_conf
def get_named_rndc_conf_path():
return os.path.join(
conf.DNS_CONFIG_DIR, MAAS_NAMED_RNDC_CONF_NAME)
def get_rndc_conf_path():
return os.path.join(conf.DNS_CONFIG_DIR, MAAS_RNDC_CONF_NAME)
def setup_rndc():
"""Writes out the two files needed to enable MAAS to use rndc commands:
MAAS_RNDC_CONF_NAME and MAAS_NAMED_RNDC_CONF_NAME, both stored in
conf.DNS_CONFIG_DIR.
"""
rndc_content, named_content = generate_rndc(
port=conf.DNS_RNDC_PORT,
include_default_controls=conf.DNS_DEFAULT_CONTROLS)
target_file = get_rndc_conf_path()
with open(target_file, "wb") as f:
f.write(rndc_content)
target_file = get_named_rndc_conf_path()
with open(target_file, "wb") as f:
f.write(named_content)
def execute_rndc_command(arguments):
"""Execute a rndc command."""
rndc_conf = os.path.join(conf.DNS_CONFIG_DIR, MAAS_RNDC_CONF_NAME)
with open(os.devnull, "ab") as devnull:
check_call(
['rndc', '-c', rndc_conf] + map(str, arguments),
stdout=devnull)
# Directory where the DNS configuration template files can be found.
TEMPLATES_PATH = os.path.join(os.path.dirname(__file__), 'templates')
class DNSConfigBase:
__metaclass__ = ABCMeta
@abstractproperty
def template_path(self):
"""Return the full path of the template to be used."""
@abstractproperty
def target_path(self):
"""Return the full path of the target file to be written."""
@property
def template_dir(self):
return TEMPLATES_PATH
@property
def access_permissions(self):
"""The access permissions for the config file."""
return 0644
@property
def target_dir(self):
return conf.DNS_CONFIG_DIR
def get_template(self):
with open(self.template_path, "r") as f:
return tempita.Template(f.read(), name=self.template_path)
def render_template(self, template, **kwargs):
try:
return template.substitute(kwargs)
except NameError as error:
raise DNSConfigFail(*error.args)
def get_context(self):
"""Dictionary containing parameters to be included in the
parameters used when rendering the template."""
return {}
def write_config(self, overwrite=True, **kwargs):
"""Write out this DNS config file.
This raises DNSConfigDirectoryMissing if any
"No such file or directory" error is raised because that would mean
that the directory containing the write to be written does not exist.
"""
try:
self.inner_write_config(overwrite=overwrite, **kwargs)
except OSError as exception:
# Only raise a DNSConfigDirectoryMissing exception if this error
# is a "No such file or directory" exception.
if exception.errno == errno.ENOENT:
raise DNSConfigDirectoryMissing(
"The directory where the DNS config files should be "
"written does not exist. Make sure the 'maas-dns' "
"package is installed on this region controller.")
else:
raise
def inner_write_config(self, overwrite=True, **kwargs):
"""Write out this DNS config file."""
template = self.get_template()
kwargs.update(self.get_context())
rendered = self.render_template(template, **kwargs)
atomic_write(
rendered, self.target_path, overwrite=overwrite,
mode=self.access_permissions)
class DNSConfig(DNSConfigBase):
"""A DNS configuration file.
Encapsulation of DNS config templates and parameter substitution.
"""
template_file_name = 'named.conf.template'
target_file_name = MAAS_NAMED_CONF_NAME
def __init__(self, zones=()):
self.zones = zones
return super(DNSConfig, self).__init__()
@property
def template_path(self):
return os.path.join(self.template_dir, self.template_file_name)
@property
def target_path(self):
return os.path.join(self.target_dir, self.target_file_name)
def get_context(self):
return {
'zones': self.zones,
'DNS_CONFIG_DIR': conf.DNS_CONFIG_DIR,
'named_rndc_conf_path': get_named_rndc_conf_path(),
'modified': unicode(datetime.today()),
}
def get_include_snippet(self):
assert '"' not in self.target_path, self.target_path
return 'include "%s";\n' % self.target_path
def shortened_reversed_ip(ip, byte_num):
"""Get a reversed version of this IP with only the significant bytes.
This method is a utility used when generating reverse zone files.
>>> shortened_reversed_ip('192.156.0.3', 2)
'3.0'
:type ip: :class:`netaddr.IPAddress`
"""
assert 0 <= byte_num <= 4, ("byte_num should be >=0 and <= 4.")
significant_octets = islice(reversed(ip.words), byte_num)
return '.'.join(imap(unicode, significant_octets))
class DNSZoneConfigBase(DNSConfigBase):
"""Base class for zone writers."""
template_file_name = 'zone.template'
def __init__(self, domain, serial=None, mapping=None, dns_ip=None):
"""
:param domain: The domain name of the forward zone.
:param serial: The serial to use in the zone file. This must increment
on each change.
:param mapping: A hostname:ip-address mapping for all known hosts in
the zone.
:param dns_ip: The IP address of the DNS server authoritative for this
zone.
"""
super(DNSZoneConfigBase, self).__init__()
self.domain = domain
self.serial = serial
self.mapping = {} if mapping is None else mapping
self.dns_ip = dns_ip
@abstractproperty
def zone_name(self):
"""Return the zone's fully-qualified name."""
@property
def template_path(self):
return os.path.join(self.template_dir, self.template_file_name)
@property
def target_path(self):
"""Return the full path of the DNS zone file."""
return os.path.join(
self.target_dir, 'zone.%s' % self.zone_name)
def inner_write_config(self, **kwargs):
"""Write out the DNS config file for this zone."""
template = self.get_template()
kwargs.update(self.get_context())
rendered = self.render_template(template, **kwargs)
incremental_write(
rendered, self.target_path, mode=self.access_permissions)
class DNSForwardZoneConfig(DNSZoneConfigBase):
"""Writes forward zone files."""
def __init__(self, *args, **kwargs):
"""See `DNSZoneConfigBase.__init__`.
:param networks: The networks that the mapping exists within.
:type networks: Sequence of :class:`netaddr.IPNetwork`
"""
networks = kwargs.pop("networks", None)
self.networks = [] if networks is None else networks
super(DNSForwardZoneConfig, self).__init__(*args, **kwargs)
@property
def zone_name(self):
"""Return the name of the forward zone."""
return self.domain
def get_cname_mapping(self):
"""Return a generator with the mapping: hostname->generated hostname.
The mapping only contains hosts for which the two host names differ.
:return: A generator of tuples: (host name, generated host name).
"""
# We filter out cases where the two host names are identical: it
# would be wrong to define a CNAME that maps to itself.
for hostname, ip in self.mapping.items():
generated_name = generated_hostname(ip)
if generated_name != hostname:
yield (hostname, generated_name)
def get_static_mapping(self):
"""Return a generator with the mapping fqdn->ip for the generated ips.
The generated mapping is the mapping between the generated hostnames
and the IP addresses for all the possible IP addresses in zone.
Note that we return a list of tuples instead of a dictionary in order
to be able to return a generator.
"""
ips = imap(unicode, chain.from_iterable(self.networks))
static_mapping = ((generated_hostname(ip), ip) for ip in ips)
# Add A record for the name server's IP.
return chain([('%s.' % self.domain, self.dns_ip)], static_mapping)
def get_context(self):
"""Return the dict used to render the DNS zone file.
That context dict is used to render the DNS zone file.
"""
return {
'domain': self.domain,
'serial': self.serial,
'modified': unicode(datetime.today()),
'mappings': {
'CNAME': self.get_cname_mapping(),
'A': self.get_static_mapping(),
}
}
class DNSReverseZoneConfig(DNSZoneConfigBase):
"""Writes reverse zone files."""
def __init__(self, *args, **kwargs):
"""See `DNSZoneConfigBase.__init__`.
:param network: The network that the mapping exists within.
:type network: :class:`netaddr.IPNetwork`
"""
self.network = kwargs.pop("network", None)
super(DNSReverseZoneConfig, self).__init__(*args, **kwargs)
@property
def zone_name(self):
"""Return the name of the reverse zone."""
broadcast, netmask = self.network.broadcast, self.network.netmask
octets = broadcast.words[:netmask.words.count(255)]
return '%s.in-addr.arpa' % '.'.join(imap(unicode, reversed(octets)))
def get_static_mapping(self):
"""Return the reverse generated mapping: (shortened) ip->fqdn.
The reverse generated mapping is the mapping between the IP addresses
and the generated hostnames for all the possible IP addresses in zone.
"""
byte_num = 4 - self.network.netmask.words.count(255)
return (
(shortened_reversed_ip(ip, byte_num),
'%s.%s.' % (generated_hostname(ip), self.domain))
for ip in self.network
)
def get_context(self):
"""Return the dict used to render the DNS reverse zone file.
That context dict is used to render the DNS reverse zone file.
"""
return {
'domain': self.domain,
'serial': self.serial,
'modified': unicode(datetime.today()),
'mappings': {
'PTR': self.get_static_mapping(),
}
}
|