| 1 |
# Authors: Martin Basti <[email protected]> |
| 2 |
# |
| 3 |
# Copyright (C) 2007-2014 Red Hat |
| 4 |
# see file 'COPYING' for use and warranty information |
| 5 |
# |
| 6 |
# This program is free software; you can redistribute it and/or modify |
| 7 |
# it under the terms of the GNU General Public License as published by |
| 8 |
# the Free Software Foundation, either version 3 of the License, or |
| 9 |
# (at your option) any later version. |
| 10 |
# |
| 11 |
# This program is distributed in the hope that it will be useful, |
| 12 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 |
# GNU General Public License for more details. |
| 15 |
# |
| 16 |
# You should have received a copy of the GNU General Public License |
| 17 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 18 |
# |
| 19 |
|
| 20 |
import copy |
| 21 |
import logging |
| 22 |
import operator |
| 23 |
import random |
| 24 |
|
| 25 |
import dns.name |
| 26 |
import dns.exception |
| 27 |
import dns.resolver |
| 28 |
import dns.rdataclass |
| 29 |
import dns.rdatatype |
| 30 |
import dns.reversename |
| 31 |
|
| 32 |
|
| 33 |
import six |
| 34 |
|
| 35 |
from ipapython.ipautil import UnsafeIPAddress |
| 36 |
|
| 37 |
if six.PY3: |
| 38 |
unicode = str |
| 39 |
|
| 40 |
logger = logging.getLogger(__name__) |
| 41 |
|
| 42 |
|
| 43 |
ipa_resolver = None |
| 44 |
|
| 45 |
|
| 46 |
def get_ipa_resolver(): |
| 47 |
global ipa_resolver |
| 48 |
if ipa_resolver is None: |
| 49 |
ipa_resolver = DNSResolver() |
| 50 |
return ipa_resolver |
| 51 |
|
| 52 |
|
| 53 |
def resolve(*args, **kwargs): |
| 54 |
return get_ipa_resolver().resolve(*args, **kwargs) |
| 55 |
|
| 56 |
|
| 57 |
def resolve_address(*args, **kwargs): |
| 58 |
return get_ipa_resolver().resolve_address(*args, **kwargs) |
| 59 |
|
| 60 |
|
| 61 |
def zone_for_name(*args, **kwargs): |
| 62 |
if "resolver" not in kwargs: |
| 63 |
kwargs["resolver"] = get_ipa_resolver() |
| 64 |
|
| 65 |
return dns.resolver.zone_for_name(*args, **kwargs) |
| 66 |
|
| 67 |
|
| 68 |
def reset_default_resolver(): |
| 69 |
"""Re-initialize ipa resolver. |
| 70 |
""" |
| 71 |
global ipa_resolver |
| 72 |
ipa_resolver = DNSResolver() |
| 73 |
|
| 74 |
|
| 75 |
class DNSResolver(dns.resolver.Resolver): |
| 76 |
"""DNS stub resolver compatible with both dnspython < 2.0.0 |
| 77 |
and dnspython >= 2.0.0. |
| 78 |
|
| 79 |
Set `use_search_by_default` attribute to `True`, which |
| 80 |
determines the default for whether the search list configured |
| 81 |
in the system's resolver configuration is used for relative |
| 82 |
names, and whether the resolver's domain may be added to relative |
| 83 |
names. |
| 84 |
|
| 85 |
Increase the default lifetime which determines the number of seconds |
| 86 |
to spend trying to get an answer to the question. dnspython 2.0.0 |
| 87 |
changes this to 5sec, while the previous one was 30sec. |
| 88 |
""" |
| 89 |
def __init__(self, *args, **kwargs): |
| 90 |
self._nameservers = None |
| 91 |
super().__init__(*args, **kwargs) |
| 92 |
self.reset_ipa_defaults() |
| 93 |
self.resolve = getattr(super(), "resolve", self.query) |
| 94 |
self.resolve_address = getattr( |
| 95 |
super(), |
| 96 |
"resolve_address", |
| 97 |
self._resolve_address |
| 98 |
) |
| 99 |
|
| 100 |
def reset_ipa_defaults(self): |
| 101 |
""" |
| 102 |
BIND's default timeout for resolver is 10sec. |
| 103 |
If that changes then it causes Timeout (instead of SERVFAIL) |
| 104 |
exception for dnspython if BIND under high load. So, let's make |
| 105 |
it the same + operation time. |
| 106 |
|
| 107 |
dnspython default is 2sec |
| 108 |
""" |
| 109 |
self.timeout = 10 + 2 |
| 110 |
|
| 111 |
# dnspython default is 5sec |
| 112 |
self.lifetime = min(self.timeout * len(self.nameservers) * 2, 45) |
| 113 |
self.use_search_by_default = True |
| 114 |
|
| 115 |
def reset(self): |
| 116 |
super().reset() |
| 117 |
self.reset_ipa_defaults() |
| 118 |
|
| 119 |
def _resolve_address(self, ip_address, *args, **kwargs): |
| 120 |
"""Query nameservers for PTR records. |
| 121 |
|
| 122 |
:param ip_address: IPv4 or IPv6 address |
| 123 |
:type ip_address: str |
| 124 |
""" |
| 125 |
return self.resolve( |
| 126 |
dns.reversename.from_address(ip_address), |
| 127 |
rdtype=dns.rdatatype.PTR, |
| 128 |
*args, |
| 129 |
**kwargs, |
| 130 |
) |
| 131 |
|
| 132 |
def read_resolv_conf(self, *args, **kwargs): |
| 133 |
""" |
| 134 |
dnspython tries nameservers sequentially(not parallel). |
| 135 |
IPA controlled BIND always listen on IPv6 if available, |
| 136 |
so no need to send requests to both IPv4 and IPv6 endpoints |
| 137 |
of the same NS(though BIND handles this). |
| 138 |
""" |
| 139 |
super().read_resolv_conf(*args, **kwargs) |
| 140 |
# deduplicate |
| 141 |
nameservers = list(dict.fromkeys(self.nameservers)) |
| 142 |
ipv6_loopback = "::1" |
| 143 |
ipv4_loopback = "127.0.0.1" |
| 144 |
if ipv6_loopback in nameservers and ipv4_loopback in nameservers: |
| 145 |
nameservers.remove(ipv4_loopback) |
| 146 |
self.nameservers = nameservers |
| 147 |
|
| 148 |
@property |
| 149 |
def nameservers(self): |
| 150 |
return self._nameservers |
| 151 |
|
| 152 |
@nameservers.setter |
| 153 |
def nameservers(self, nameservers): |
| 154 |
""" |
| 155 |
*nameservers*, a ``list`` of nameservers with optional ports: |
| 156 |
"SERVER_IP port PORT_NUMBER". |
| 157 |
|
| 158 |
Overloads dns.resolver.Resolver.nameservers setter to split off ports |
| 159 |
into nameserver_ports after setting nameservers successfully with the |
| 160 |
setter in dns.resolver.Resolver. |
| 161 |
""" |
| 162 |
# Get nameserver_ports if it is already set |
| 163 |
if hasattr(self, "nameserver_ports"): |
| 164 |
nameserver_ports = self.nameserver_ports |
| 165 |
else: |
| 166 |
nameserver_ports = {} |
| 167 |
|
| 168 |
# Check nameserver items in list and split out converted port number |
| 169 |
# into nameserver_ports: { nameserver: port } |
| 170 |
if isinstance(nameservers, list): |
| 171 |
_nameservers = [] |
| 172 |
for nameserver in nameservers: |
| 173 |
splits = nameserver.split() |
| 174 |
if len(splits) == 3 and splits[1] == "port": |
| 175 |
nameserver = splits[0] |
| 176 |
try: |
| 177 |
port = int(splits[2]) |
| 178 |
if port < 0 or port > 65535: |
| 179 |
raise ValueError() |
| 180 |
except ValueError: |
| 181 |
raise ValueError( |
| 182 |
"invalid nameserver: %s is not a valid port" % |
| 183 |
splits[2]) |
| 184 |
nameserver_ports[nameserver] = port |
| 185 |
_nameservers.append(nameserver) |
| 186 |
nameservers = _nameservers |
| 187 |
|
| 188 |
# Call dns.resolver.Resolver.nameservers setter |
| 189 |
if hasattr(dns.resolver.Resolver, "nameservers"): |
| 190 |
dns.resolver.Resolver.nameservers.__set__(self, nameservers) |
| 191 |
else: |
| 192 |
# old dnspython (<2) doesn't have 'nameservers' property |
| 193 |
self._nameservers = nameservers |
| 194 |
# Set nameserver_ports after successfull call to setter |
| 195 |
self.nameserver_ports = nameserver_ports |
| 196 |
|
| 197 |
|
| 198 |
class DNSZoneAlreadyExists(dns.exception.DNSException): |
| 199 |
supp_kwargs = {'zone', 'ns'} |
| 200 |
fmt = (u"DNS zone {zone} already exists in DNS " |
| 201 |
"and is handled by server(s): {ns}") |
| 202 |
|
| 203 |
|
| 204 |
@six.python_2_unicode_compatible |
| 205 |
class DNSName(dns.name.Name): |
| 206 |
labels = None # make pylint happy |
| 207 |
|
| 208 |
@classmethod |
| 209 |
def from_text(cls, labels, origin=None): |
| 210 |
return cls(dns.name.from_text(labels, origin)) |
| 211 |
|
| 212 |
def __init__(self, labels, origin=None): |
| 213 |
try: |
| 214 |
if isinstance(labels, str): |
| 215 |
labels = dns.name.from_text(unicode(labels), origin).labels |
| 216 |
elif isinstance(labels, dns.name.Name): |
| 217 |
labels = labels.labels |
| 218 |
|
| 219 |
super(DNSName, self).__init__(labels) |
| 220 |
except UnicodeError as e: |
| 221 |
# dnspython bug, an invalid domain name returns the UnicodeError |
| 222 |
# instead of a dns.exception |
| 223 |
raise dns.exception.SyntaxError(e) |
| 224 |
|
| 225 |
def __bool__(self): |
| 226 |
#dns.name.from_text('@') is represented like empty tuple |
| 227 |
#we need to acting '@' as nonzero value |
| 228 |
return True |
| 229 |
|
| 230 |
__nonzero__ = __bool__ # for Python 2 |
| 231 |
|
| 232 |
def __copy__(self): |
| 233 |
return DNSName(self.labels) |
| 234 |
|
| 235 |
def __deepcopy__(self, memo): |
| 236 |
return DNSName(copy.deepcopy(self.labels, memo)) |
| 237 |
|
| 238 |
def __str__(self): |
| 239 |
return self.to_unicode() |
| 240 |
|
| 241 |
# method ToASCII named by RFC 3490 and python standard library |
| 242 |
if six.PY2: |
| 243 |
def ToASCII(self): |
| 244 |
# must be unicode string in Py2 |
| 245 |
return self.to_text().decode('ascii') |
| 246 |
else: |
| 247 |
def ToASCII(self): |
| 248 |
return self.to_text() |
| 249 |
|
| 250 |
def canonicalize(self): |
| 251 |
return DNSName(super(DNSName, self).canonicalize()) |
| 252 |
|
| 253 |
def concatenate(self, other): |
| 254 |
return DNSName(super(DNSName, self).concatenate(other)) |
| 255 |
|
| 256 |
def relativize(self, origin): |
| 257 |
return DNSName(super(DNSName, self).relativize(origin)) |
| 258 |
|
| 259 |
def derelativize(self, origin): |
| 260 |
return DNSName(super(DNSName, self).derelativize(origin)) |
| 261 |
|
| 262 |
def choose_relativity(self, origin=None, relativize=True): |
| 263 |
return DNSName(super(DNSName, self).choose_relativity(origin=origin, |
| 264 |
relativize=relativize)) |
| 265 |
|
| 266 |
def make_absolute(self): |
| 267 |
return self.derelativize(self.root) |
| 268 |
|
| 269 |
def is_idn(self): |
| 270 |
return any(label.startswith('xn--') for label in self.labels) |
| 271 |
|
| 272 |
def is_ip4_reverse(self): |
| 273 |
return self.is_subdomain(self.ip4_rev_zone) |
| 274 |
|
| 275 |
def is_ip6_reverse(self): |
| 276 |
return self.is_subdomain(self.ip6_rev_zone) |
| 277 |
|
| 278 |
def is_reverse(self): |
| 279 |
return self.is_ip4_reverse() or self.is_ip6_reverse() |
| 280 |
|
| 281 |
def is_empty(self): |
| 282 |
return len(self.labels) == 0 |
| 283 |
|
| 284 |
|
| 285 |
#DNS public constants |
| 286 |
DNSName.root = DNSName(dns.name.root) # '.' |
| 287 |
DNSName.empty = DNSName(dns.name.empty) # '@' |
| 288 |
DNSName.ip4_rev_zone = DNSName(('in-addr', 'arpa', '')) |
| 289 |
DNSName.ip6_rev_zone = DNSName(('ip6', 'arpa', '')) |
| 290 |
|
| 291 |
# Empty zones are defined in various RFCs. BIND is by default serving them. |
| 292 |
# This constat should contain everything listed in |
| 293 |
# IANA registry "Locally-Served DNS Zones" |
| 294 |
# URL: http://www.iana.org/assignments/locally-served-dns-zones |
| 295 |
# + AS112 zone defined in RFC 7534. It is not in the registry for some |
| 296 |
# reason but BIND 9.10 is serving it as automatic empty zones. |
| 297 |
EMPTY_ZONES = [DNSName(aez).make_absolute() for aez in [ |
| 298 |
# RFC 1918 |
| 299 |
"10.IN-ADDR.ARPA", "16.172.IN-ADDR.ARPA", "17.172.IN-ADDR.ARPA", |
| 300 |
"18.172.IN-ADDR.ARPA", "19.172.IN-ADDR.ARPA", "20.172.IN-ADDR.ARPA", |
| 301 |
"21.172.IN-ADDR.ARPA", "22.172.IN-ADDR.ARPA", "23.172.IN-ADDR.ARPA", |
| 302 |
"24.172.IN-ADDR.ARPA", "25.172.IN-ADDR.ARPA", "26.172.IN-ADDR.ARPA", |
| 303 |
"27.172.IN-ADDR.ARPA", "28.172.IN-ADDR.ARPA", "29.172.IN-ADDR.ARPA", |
| 304 |
"30.172.IN-ADDR.ARPA", "31.172.IN-ADDR.ARPA", "168.192.IN-ADDR.ARPA", |
| 305 |
# RFC 6598 |
| 306 |
"64.100.IN-ADDR.ARPA", "65.100.IN-ADDR.ARPA", "66.100.IN-ADDR.ARPA", |
| 307 |
"67.100.IN-ADDR.ARPA", "68.100.IN-ADDR.ARPA", "69.100.IN-ADDR.ARPA", |
| 308 |
"70.100.IN-ADDR.ARPA", "71.100.IN-ADDR.ARPA", "72.100.IN-ADDR.ARPA", |
| 309 |
"73.100.IN-ADDR.ARPA", "74.100.IN-ADDR.ARPA", "75.100.IN-ADDR.ARPA", |
| 310 |
"76.100.IN-ADDR.ARPA", "77.100.IN-ADDR.ARPA", "78.100.IN-ADDR.ARPA", |
| 311 |
"79.100.IN-ADDR.ARPA", "80.100.IN-ADDR.ARPA", "81.100.IN-ADDR.ARPA", |
| 312 |
"82.100.IN-ADDR.ARPA", "83.100.IN-ADDR.ARPA", "84.100.IN-ADDR.ARPA", |
| 313 |
"85.100.IN-ADDR.ARPA", "86.100.IN-ADDR.ARPA", "87.100.IN-ADDR.ARPA", |
| 314 |
"88.100.IN-ADDR.ARPA", "89.100.IN-ADDR.ARPA", "90.100.IN-ADDR.ARPA", |
| 315 |
"91.100.IN-ADDR.ARPA", "92.100.IN-ADDR.ARPA", "93.100.IN-ADDR.ARPA", |
| 316 |
"94.100.IN-ADDR.ARPA", "95.100.IN-ADDR.ARPA", "96.100.IN-ADDR.ARPA", |
| 317 |
"97.100.IN-ADDR.ARPA", "98.100.IN-ADDR.ARPA", "99.100.IN-ADDR.ARPA", |
| 318 |
"100.100.IN-ADDR.ARPA", "101.100.IN-ADDR.ARPA", |
| 319 |
"102.100.IN-ADDR.ARPA", "103.100.IN-ADDR.ARPA", |
| 320 |
"104.100.IN-ADDR.ARPA", "105.100.IN-ADDR.ARPA", |
| 321 |
"106.100.IN-ADDR.ARPA", "107.100.IN-ADDR.ARPA", |
| 322 |
"108.100.IN-ADDR.ARPA", "109.100.IN-ADDR.ARPA", |
| 323 |
"110.100.IN-ADDR.ARPA", "111.100.IN-ADDR.ARPA", |
| 324 |
"112.100.IN-ADDR.ARPA", "113.100.IN-ADDR.ARPA", |
| 325 |
"114.100.IN-ADDR.ARPA", "115.100.IN-ADDR.ARPA", |
| 326 |
"116.100.IN-ADDR.ARPA", "117.100.IN-ADDR.ARPA", |
| 327 |
"118.100.IN-ADDR.ARPA", "119.100.IN-ADDR.ARPA", |
| 328 |
"120.100.IN-ADDR.ARPA", "121.100.IN-ADDR.ARPA", |
| 329 |
"122.100.IN-ADDR.ARPA", "123.100.IN-ADDR.ARPA", |
| 330 |
"124.100.IN-ADDR.ARPA", "125.100.IN-ADDR.ARPA", |
| 331 |
"126.100.IN-ADDR.ARPA", "127.100.IN-ADDR.ARPA", |
| 332 |
# RFC 5735 and RFC 5737 |
| 333 |
"0.IN-ADDR.ARPA", "127.IN-ADDR.ARPA", "254.169.IN-ADDR.ARPA", |
| 334 |
"2.0.192.IN-ADDR.ARPA", "100.51.198.IN-ADDR.ARPA", |
| 335 |
"113.0.203.IN-ADDR.ARPA", "255.255.255.255.IN-ADDR.ARPA", |
| 336 |
# Local IPv6 Unicast Addresses |
| 337 |
"0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.IP6.ARPA", |
| 338 |
"1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.IP6.ARPA", |
| 339 |
# LOCALLY ASSIGNED LOCAL ADDRESS SCOPE |
| 340 |
"D.F.IP6.ARPA", "8.E.F.IP6.ARPA", "9.E.F.IP6.ARPA", "A.E.F.IP6.ARPA", |
| 341 |
"B.E.F.IP6.ARPA", |
| 342 |
# Example Prefix, RFC 3849. |
| 343 |
"8.B.D.0.1.0.0.2.IP6.ARPA", |
| 344 |
# RFC 7534 |
| 345 |
"EMPTY.AS112.ARPA", |
| 346 |
]] |
| 347 |
|
| 348 |
|
| 349 |
def assert_absolute_dnsname(name): |
| 350 |
"""Raise AssertionError if name is not DNSName or is not absolute. |
| 351 |
|
| 352 |
>>> assert_absolute_dnsname(DNSName('absolute.name.example.')) |
| 353 |
>>> assert_absolute_dnsname(DNSName('relative.name.example')) |
| 354 |
Traceback (most recent call last): |
| 355 |
... |
| 356 |
AssertionError: name must be absolute, ... |
| 357 |
>>> assert_absolute_dnsname('absolute.string.example.') |
| 358 |
Traceback (most recent call last): |
| 359 |
... |
| 360 |
AssertionError: name must be DNSName instance, ... |
| 361 |
""" |
| 362 |
|
| 363 |
assert isinstance(name, DNSName), ("name must be DNSName instance, " |
| 364 |
"got '%s'" % type(name)) |
| 365 |
assert name.is_absolute(), "name must be absolute, got '%s'" % name |
| 366 |
|
| 367 |
|
| 368 |
def is_auto_empty_zone(zone): |
| 369 |
"""True if specified zone name exactly matches an automatic empty zone. |
| 370 |
|
| 371 |
>>> is_auto_empty_zone(DNSName('in-addr.arpa.')) |
| 372 |
False |
| 373 |
>>> is_auto_empty_zone(DNSName('10.in-addr.arpa.')) |
| 374 |
True |
| 375 |
>>> is_auto_empty_zone(DNSName('1.10.in-addr.arpa.')) |
| 376 |
False |
| 377 |
>>> is_auto_empty_zone(DNSName('10.in-addr.arpa')) |
| 378 |
Traceback (most recent call last): |
| 379 |
... |
| 380 |
AssertionError: ... |
| 381 |
""" |
| 382 |
assert_absolute_dnsname(zone) |
| 383 |
return zone in EMPTY_ZONES |
| 384 |
|
| 385 |
|
| 386 |
def inside_auto_empty_zone(name): |
| 387 |
"""True if specified absolute name is a subdomain of an automatic empty |
| 388 |
zone. |
| 389 |
|
| 390 |
DNS domain is a subdomain of itself so this function |
| 391 |
returns True for zone apexes, too. |
| 392 |
|
| 393 |
>>> inside_auto_empty_zone(DNSName('in-addr.arpa.')) |
| 394 |
False |
| 395 |
>>> inside_auto_empty_zone(DNSName('10.in-addr.arpa.')) |
| 396 |
True |
| 397 |
>>> inside_auto_empty_zone(DNSName('1.10.in-addr.arpa.')) |
| 398 |
True |
| 399 |
>>> inside_auto_empty_zone(DNSName('1.10.in-addr.arpa')) |
| 400 |
Traceback (most recent call last): |
| 401 |
... |
| 402 |
AssertionError: ... |
| 403 |
""" |
| 404 |
assert_absolute_dnsname(name) |
| 405 |
for aez in EMPTY_ZONES: |
| 406 |
if name.is_subdomain(aez): |
| 407 |
return True |
| 408 |
return False |
| 409 |
|
| 410 |
|
| 411 |
def related_to_auto_empty_zone(name): |
| 412 |
"""True if specified absolute name is a sub/superdomain of an automatic |
| 413 |
empty zone. |
| 414 |
|
| 415 |
DNS domain is a subdomain of itself so this function |
| 416 |
returns True for zone apexes, too. |
| 417 |
|
| 418 |
>>> related_to_auto_empty_zone(DNSName('.')) |
| 419 |
True |
| 420 |
>>> related_to_auto_empty_zone(DNSName('in-addr.arpa.')) |
| 421 |
True |
| 422 |
>>> related_to_auto_empty_zone(DNSName('10.in-addr.arpa.')) |
| 423 |
True |
| 424 |
>>> related_to_auto_empty_zone(DNSName('1.10.in-addr.arpa.')) |
| 425 |
True |
| 426 |
>>> related_to_auto_empty_zone(DNSName('unrelated.example.')) |
| 427 |
False |
| 428 |
>>> related_to_auto_empty_zone(DNSName('1.10.in-addr.arpa')) |
| 429 |
Traceback (most recent call last): |
| 430 |
... |
| 431 |
AssertionError: ... |
| 432 |
""" |
| 433 |
assert_absolute_dnsname(name) |
| 434 |
relations = {dns.name.NAMERELN_SUBDOMAIN, |
| 435 |
dns.name.NAMERELN_EQUAL, |
| 436 |
dns.name.NAMERELN_SUPERDOMAIN} |
| 437 |
return any(name.fullcompare(aez)[0] in relations |
| 438 |
for aez in EMPTY_ZONES) |
| 439 |
|
| 440 |
|
| 441 |
def has_empty_zone_addresses(hostname): |
| 442 |
"""Detect if given host is using IP address belonging to |
| 443 |
an automatic empty zone. |
| 444 |
|
| 445 |
Information from --ip-address option used in installed is lost by |
| 446 |
the time when upgrade is run. Use IP addresses from DNS as best |
| 447 |
approximation. |
| 448 |
|
| 449 |
This is brain-dead and duplicates logic from DNS installer |
| 450 |
but I did not find other way around. |
| 451 |
""" |
| 452 |
ip_addresses = resolve_ip_addresses(hostname) |
| 453 |
return any( |
| 454 |
inside_auto_empty_zone(DNSName(ip.reverse_dns)) |
| 455 |
for ip in ip_addresses |
| 456 |
) |
| 457 |
|
| 458 |
|
| 459 |
def resolve_rrsets(fqdn, rdtypes): |
| 460 |
""" |
| 461 |
Get Resource Record sets for given FQDN. |
| 462 |
CNAME chain is followed during resolution |
| 463 |
but CNAMEs are not returned in the resulting rrset. |
| 464 |
|
| 465 |
:returns: |
| 466 |
set of dns.rrset.RRset objects, can be empty |
| 467 |
if the FQDN does not exist or if none of rrtypes exist |
| 468 |
""" |
| 469 |
# empty set of rdtypes would always return empty set of rrsets |
| 470 |
assert rdtypes, "rdtypes must not be empty" |
| 471 |
|
| 472 |
if not isinstance(fqdn, DNSName): |
| 473 |
fqdn = DNSName(fqdn) |
| 474 |
|
| 475 |
fqdn = fqdn.make_absolute() |
| 476 |
rrsets = [] |
| 477 |
for rdtype in rdtypes: |
| 478 |
try: |
| 479 |
answer = resolve(fqdn, rdtype) |
| 480 |
logger.debug('found %d %s records for %s: %s', |
| 481 |
len(answer), |
| 482 |
rdtype, |
| 483 |
fqdn, |
| 484 |
' '.join(str(rr) for rr in answer)) |
| 485 |
rrsets.append(answer.rrset) |
| 486 |
except dns.resolver.NXDOMAIN as ex: |
| 487 |
logger.debug('%s', ex) |
| 488 |
break # no such FQDN, do not iterate |
| 489 |
except dns.resolver.NoAnswer as ex: |
| 490 |
logger.debug('%s', ex) # record type does not exist for given FQDN |
| 491 |
except dns.exception.DNSException as ex: |
| 492 |
logger.error('DNS query for %s %s failed: %s', fqdn, rdtype, ex) |
| 493 |
raise |
| 494 |
|
| 495 |
return rrsets |
| 496 |
|
| 497 |
|
| 498 |
def resolve_ip_addresses(fqdn): |
| 499 |
"""Get IP addresses from DNS A/AAAA records for given host (using DNS). |
| 500 |
:returns: |
| 501 |
list of IP addresses as UnsafeIPAddress objects |
| 502 |
""" |
| 503 |
rrsets = resolve_rrsets(fqdn, ['A', 'AAAA']) |
| 504 |
ip_addresses = set() |
| 505 |
for rrset in rrsets: |
| 506 |
ip_addresses.update({UnsafeIPAddress(ip) for ip in rrset}) |
| 507 |
return ip_addresses |
| 508 |
|
| 509 |
|
| 510 |
def check_zone_overlap(zone, raise_on_error=True): |
| 511 |
logger.info("Checking DNS domain %s, please wait ...", zone) |
| 512 |
if not isinstance(zone, DNSName): |
| 513 |
zone = DNSName(zone).make_absolute() |
| 514 |
|
| 515 |
# automatic empty zones always exist so checking them is pointless, |
| 516 |
# do not report them to avoid meaningless error messages |
| 517 |
if is_auto_empty_zone(zone): |
| 518 |
return |
| 519 |
|
| 520 |
try: |
| 521 |
containing_zone = zone_for_name(zone) |
| 522 |
except dns.exception.DNSException as e: |
| 523 |
msg = ("DNS check for domain %s failed: %s." % (zone, e)) |
| 524 |
if raise_on_error: |
| 525 |
if isinstance(e, dns.resolver.NoNameservers): |
| 526 |
# Show warning and continue in case we've got SERVFAIL |
| 527 |
# because we are supposedly going to create this reverse zone |
| 528 |
logger.warning('%s', msg) |
| 529 |
return |
| 530 |
else: |
| 531 |
raise ValueError(msg) |
| 532 |
else: |
| 533 |
logger.warning('%s', msg) |
| 534 |
return |
| 535 |
|
| 536 |
if containing_zone == zone: |
| 537 |
try: |
| 538 |
ns = [ans.to_text() for ans in resolve(zone, 'NS')] |
| 539 |
except dns.exception.DNSException as e: |
| 540 |
logger.debug("Failed to resolve nameserver(s) for domain %s: %s", |
| 541 |
zone, e) |
| 542 |
ns = [] |
| 543 |
|
| 544 |
raise DNSZoneAlreadyExists(zone=zone.to_text(), ns=ns) |
| 545 |
|
| 546 |
|
| 547 |
def _mix_weight(records): |
| 548 |
"""Weighted population sorting for records with same priority |
| 549 |
""" |
| 550 |
# trivial case |
| 551 |
if len(records) <= 1: |
| 552 |
return records |
| 553 |
|
| 554 |
# Optimization for common case: If all weights are the same (e.g. 0), |
| 555 |
# just shuffle the records, which is about four times faster. |
| 556 |
if all(rr.weight == records[0].weight for rr in records): |
| 557 |
random.shuffle(records) |
| 558 |
return records |
| 559 |
|
| 560 |
noweight = 0.01 # give records with 0 weight a small chance |
| 561 |
result = [] |
| 562 |
records = set(records) |
| 563 |
while len(records) > 1: |
| 564 |
# Compute the sum of the weights of those RRs. Then choose a |
| 565 |
# uniform random number between 0 and the sum computed (inclusive). |
| 566 |
urn = random.uniform(0, sum(rr.weight or noweight for rr in records)) |
| 567 |
# Select the RR whose running sum value is the first in the selected |
| 568 |
# order which is greater than or equal to the random number selected. |
| 569 |
acc = 0. |
| 570 |
for rr in records.copy(): |
| 571 |
acc += rr.weight or noweight |
| 572 |
if acc >= urn: |
| 573 |
records.remove(rr) |
| 574 |
result.append(rr) |
| 575 |
if records: |
| 576 |
result.append(records.pop()) |
| 577 |
return result |
| 578 |
|
| 579 |
|
| 580 |
def sort_prio_weight(records): |
| 581 |
"""RFC 2782 sorting algorithm for SRV and URI records |
| 582 |
|
| 583 |
RFC 2782 defines a sorting algorithms for SRV records, that is also used |
| 584 |
for sorting URI records. Records are sorted by priority and than randomly |
| 585 |
shuffled according to weight. |
| 586 |
|
| 587 |
This implementation also removes duplicate entries. |
| 588 |
""" |
| 589 |
# order records by priority |
| 590 |
records = sorted(records, key=operator.attrgetter("priority")) |
| 591 |
|
| 592 |
# remove duplicate entries |
| 593 |
uniquerecords = [] |
| 594 |
seen = set() |
| 595 |
for rr in records: |
| 596 |
# A SRV record has target and port, URI just has target. |
| 597 |
target = (rr.target, getattr(rr, "port", None)) |
| 598 |
if target not in seen: |
| 599 |
uniquerecords.append(rr) |
| 600 |
seen.add(target) |
| 601 |
|
| 602 |
# weighted randomization of entries with same priority |
| 603 |
result = [] |
| 604 |
sameprio = [] |
| 605 |
for rr in uniquerecords: |
| 606 |
# add all items with same priority in a bucket |
| 607 |
if not sameprio or sameprio[0].priority == rr.priority: |
| 608 |
sameprio.append(rr) |
| 609 |
else: |
| 610 |
# got different priority, shuffle bucket |
| 611 |
result.extend(_mix_weight(sameprio)) |
| 612 |
# start a new priority list |
| 613 |
sameprio = [rr] |
| 614 |
# add last batch of records with same priority |
| 615 |
if sameprio: |
| 616 |
result.extend(_mix_weight(sameprio)) |
| 617 |
return result |
| 618 |
|
| 619 |
|
| 620 |
def query_srv(qname, resolver=None, **kwargs): |
| 621 |
"""Query SRV records and sort reply according to RFC 2782 |
| 622 |
|
| 623 |
:param qname: query name, _service._proto.domain. |
| 624 |
:return: list of dns.rdtypes.IN.SRV.SRV instances |
| 625 |
""" |
| 626 |
if resolver is None: |
| 627 |
resolve_f = resolve |
| 628 |
else: |
| 629 |
resolve_f = getattr(resolver, "resolve", resolver.query) |
| 630 |
answer = resolve_f(qname, rdtype=dns.rdatatype.SRV, **kwargs) |
| 631 |
return sort_prio_weight(answer) |