| 1 |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license |
| 2 |
|
| 3 |
# Copyright (C) 2003-2017 Nominum, Inc. |
| 4 |
# |
| 5 |
# Permission to use, copy, modify, and distribute this software and its |
| 6 |
# documentation for any purpose with or without fee is hereby granted, |
| 7 |
# provided that the above copyright notice and this permission notice |
| 8 |
# appear in all copies. |
| 9 |
# |
| 10 |
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES |
| 11 |
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
| 12 |
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR |
| 13 |
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
| 14 |
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
| 15 |
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT |
| 16 |
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
| 17 |
|
| 18 |
"""Asynchronous DNS stub resolver.""" |
| 19 |
|
| 20 |
import socket |
| 21 |
import time |
| 22 |
from typing import Any, Dict, List |
| 23 |
|
| 24 |
import dns._ddr |
| 25 |
import dns.asyncbackend |
| 26 |
import dns.asyncquery |
| 27 |
import dns.exception |
| 28 |
import dns.inet |
| 29 |
import dns.name |
| 30 |
import dns.nameserver |
| 31 |
import dns.query |
| 32 |
import dns.rdataclass |
| 33 |
import dns.rdatatype |
| 34 |
import dns.resolver # lgtm[py/import-and-import-from] |
| 35 |
import dns.reversename |
| 36 |
|
| 37 |
# import some resolver symbols for brevity |
| 38 |
from dns.resolver import NXDOMAIN, NoAnswer, NoRootSOA, NotAbsolute |
| 39 |
|
| 40 |
# for indentation purposes below |
| 41 |
_udp = dns.asyncquery.udp |
| 42 |
_tcp = dns.asyncquery.tcp |
| 43 |
|
| 44 |
|
| 45 |
class Resolver(dns.resolver.BaseResolver): |
| 46 |
"""Asynchronous DNS stub resolver.""" |
| 47 |
|
| 48 |
async def resolve( |
| 49 |
self, |
| 50 |
qname: dns.name.Name | str, |
| 51 |
rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, |
| 52 |
rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, |
| 53 |
tcp: bool = False, |
| 54 |
source: str | None = None, |
| 55 |
raise_on_no_answer: bool = True, |
| 56 |
source_port: int = 0, |
| 57 |
lifetime: float | None = None, |
| 58 |
search: bool | None = None, |
| 59 |
backend: dns.asyncbackend.Backend | None = None, |
| 60 |
) -> dns.resolver.Answer: |
| 61 |
"""Query nameservers asynchronously to find the answer to the question. |
| 62 |
|
| 63 |
*backend*, a ``dns.asyncbackend.Backend``, or ``None``. If ``None``, |
| 64 |
the default, then dnspython will use the default backend. |
| 65 |
|
| 66 |
See :py:func:`dns.resolver.Resolver.resolve()` for the |
| 67 |
documentation of the other parameters, exceptions, and return |
| 68 |
type of this method. |
| 69 |
""" |
| 70 |
|
| 71 |
resolution = dns.resolver._Resolution( |
| 72 |
self, qname, rdtype, rdclass, tcp, raise_on_no_answer, search |
| 73 |
) |
| 74 |
if not backend: |
| 75 |
backend = dns.asyncbackend.get_default_backend() |
| 76 |
start = time.time() |
| 77 |
while True: |
| 78 |
(request, answer) = resolution.next_request() |
| 79 |
# Note we need to say "if answer is not None" and not just |
| 80 |
# "if answer" because answer implements __len__, and python |
| 81 |
# will call that. We want to return if we have an answer |
| 82 |
# object, including in cases where its length is 0. |
| 83 |
if answer is not None: |
| 84 |
# cache hit! |
| 85 |
return answer |
| 86 |
assert request is not None # needed for type checking |
| 87 |
done = False |
| 88 |
while not done: |
| 89 |
(nameserver, tcp, backoff) = resolution.next_nameserver() |
| 90 |
if backoff: |
| 91 |
await backend.sleep(backoff) |
| 92 |
timeout = self._compute_timeout(start, lifetime, resolution.errors) |
| 93 |
try: |
| 94 |
response = await nameserver.async_query( |
| 95 |
request, |
| 96 |
timeout=timeout, |
| 97 |
source=source, |
| 98 |
source_port=source_port, |
| 99 |
max_size=tcp, |
| 100 |
backend=backend, |
| 101 |
) |
| 102 |
except Exception as ex: |
| 103 |
(_, done) = resolution.query_result(None, ex) |
| 104 |
continue |
| 105 |
(answer, done) = resolution.query_result(response, None) |
| 106 |
# Note we need to say "if answer is not None" and not just |
| 107 |
# "if answer" because answer implements __len__, and python |
| 108 |
# will call that. We want to return if we have an answer |
| 109 |
# object, including in cases where its length is 0. |
| 110 |
if answer is not None: |
| 111 |
return answer |
| 112 |
|
| 113 |
async def resolve_address( |
| 114 |
self, ipaddr: str, *args: Any, **kwargs: Any |
| 115 |
) -> dns.resolver.Answer: |
| 116 |
"""Use an asynchronous resolver to run a reverse query for PTR |
| 117 |
records. |
| 118 |
|
| 119 |
This utilizes the resolve() method to perform a PTR lookup on the |
| 120 |
specified IP address. |
| 121 |
|
| 122 |
*ipaddr*, a ``str``, the IPv4 or IPv6 address you want to get |
| 123 |
the PTR record for. |
| 124 |
|
| 125 |
All other arguments that can be passed to the resolve() function |
| 126 |
except for rdtype and rdclass are also supported by this |
| 127 |
function. |
| 128 |
|
| 129 |
""" |
| 130 |
# We make a modified kwargs for type checking happiness, as otherwise |
| 131 |
# we get a legit warning about possibly having rdtype and rdclass |
| 132 |
# in the kwargs more than once. |
| 133 |
modified_kwargs: Dict[str, Any] = {} |
| 134 |
modified_kwargs.update(kwargs) |
| 135 |
modified_kwargs["rdtype"] = dns.rdatatype.PTR |
| 136 |
modified_kwargs["rdclass"] = dns.rdataclass.IN |
| 137 |
return await self.resolve( |
| 138 |
dns.reversename.from_address(ipaddr), *args, **modified_kwargs |
| 139 |
) |
| 140 |
|
| 141 |
async def resolve_name( |
| 142 |
self, |
| 143 |
name: dns.name.Name | str, |
| 144 |
family: int = socket.AF_UNSPEC, |
| 145 |
**kwargs: Any, |
| 146 |
) -> dns.resolver.HostAnswers: |
| 147 |
"""Use an asynchronous resolver to query for address records. |
| 148 |
|
| 149 |
This utilizes the resolve() method to perform A and/or AAAA lookups on |
| 150 |
the specified name. |
| 151 |
|
| 152 |
*qname*, a ``dns.name.Name`` or ``str``, the name to resolve. |
| 153 |
|
| 154 |
*family*, an ``int``, the address family. If socket.AF_UNSPEC |
| 155 |
(the default), both A and AAAA records will be retrieved. |
| 156 |
|
| 157 |
All other arguments that can be passed to the resolve() function |
| 158 |
except for rdtype and rdclass are also supported by this |
| 159 |
function. |
| 160 |
""" |
| 161 |
# We make a modified kwargs for type checking happiness, as otherwise |
| 162 |
# we get a legit warning about possibly having rdtype and rdclass |
| 163 |
# in the kwargs more than once. |
| 164 |
modified_kwargs: Dict[str, Any] = {} |
| 165 |
modified_kwargs.update(kwargs) |
| 166 |
modified_kwargs.pop("rdtype", None) |
| 167 |
modified_kwargs["rdclass"] = dns.rdataclass.IN |
| 168 |
|
| 169 |
if family == socket.AF_INET: |
| 170 |
v4 = await self.resolve(name, dns.rdatatype.A, **modified_kwargs) |
| 171 |
return dns.resolver.HostAnswers.make(v4=v4) |
| 172 |
elif family == socket.AF_INET6: |
| 173 |
v6 = await self.resolve(name, dns.rdatatype.AAAA, **modified_kwargs) |
| 174 |
return dns.resolver.HostAnswers.make(v6=v6) |
| 175 |
elif family != socket.AF_UNSPEC: |
| 176 |
raise NotImplementedError(f"unknown address family {family}") |
| 177 |
|
| 178 |
raise_on_no_answer = modified_kwargs.pop("raise_on_no_answer", True) |
| 179 |
lifetime = modified_kwargs.pop("lifetime", None) |
| 180 |
start = time.time() |
| 181 |
v6 = await self.resolve( |
| 182 |
name, |
| 183 |
dns.rdatatype.AAAA, |
| 184 |
raise_on_no_answer=False, |
| 185 |
lifetime=self._compute_timeout(start, lifetime), |
| 186 |
**modified_kwargs, |
| 187 |
) |
| 188 |
# Note that setting name ensures we query the same name |
| 189 |
# for A as we did for AAAA. (This is just in case search lists |
| 190 |
# are active by default in the resolver configuration and |
| 191 |
# we might be talking to a server that says NXDOMAIN when it |
| 192 |
# wants to say NOERROR no data. |
| 193 |
name = v6.qname |
| 194 |
v4 = await self.resolve( |
| 195 |
name, |
| 196 |
dns.rdatatype.A, |
| 197 |
raise_on_no_answer=False, |
| 198 |
lifetime=self._compute_timeout(start, lifetime), |
| 199 |
**modified_kwargs, |
| 200 |
) |
| 201 |
answers = dns.resolver.HostAnswers.make( |
| 202 |
v6=v6, v4=v4, add_empty=not raise_on_no_answer |
| 203 |
) |
| 204 |
if not answers: |
| 205 |
raise NoAnswer(response=v6.response) |
| 206 |
return answers |
| 207 |
|
| 208 |
# pylint: disable=redefined-outer-name |
| 209 |
|
| 210 |
async def canonical_name(self, name: dns.name.Name | str) -> dns.name.Name: |
| 211 |
"""Determine the canonical name of *name*. |
| 212 |
|
| 213 |
The canonical name is the name the resolver uses for queries |
| 214 |
after all CNAME and DNAME renamings have been applied. |
| 215 |
|
| 216 |
*name*, a ``dns.name.Name`` or ``str``, the query name. |
| 217 |
|
| 218 |
This method can raise any exception that ``resolve()`` can |
| 219 |
raise, other than ``dns.resolver.NoAnswer`` and |
| 220 |
``dns.resolver.NXDOMAIN``. |
| 221 |
|
| 222 |
Returns a ``dns.name.Name``. |
| 223 |
""" |
| 224 |
try: |
| 225 |
answer = await self.resolve(name, raise_on_no_answer=False) |
| 226 |
canonical_name = answer.canonical_name |
| 227 |
except dns.resolver.NXDOMAIN as e: |
| 228 |
canonical_name = e.canonical_name |
| 229 |
return canonical_name |
| 230 |
|
| 231 |
async def try_ddr(self, lifetime: float = 5.0) -> None: |
| 232 |
"""Try to update the resolver's nameservers using Discovery of Designated |
| 233 |
Resolvers (DDR). If successful, the resolver will subsequently use |
| 234 |
DNS-over-HTTPS or DNS-over-TLS for future queries. |
| 235 |
|
| 236 |
*lifetime*, a float, is the maximum time to spend attempting DDR. The default |
| 237 |
is 5 seconds. |
| 238 |
|
| 239 |
If the SVCB query is successful and results in a non-empty list of nameservers, |
| 240 |
then the resolver's nameservers are set to the returned servers in priority |
| 241 |
order. |
| 242 |
|
| 243 |
The current implementation does not use any address hints from the SVCB record, |
| 244 |
nor does it resolve addresses for the SCVB target name, rather it assumes that |
| 245 |
the bootstrap nameserver will always be one of the addresses and uses it. |
| 246 |
A future revision to the code may offer fuller support. The code verifies that |
| 247 |
the bootstrap nameserver is in the Subject Alternative Name field of the |
| 248 |
TLS certficate. |
| 249 |
""" |
| 250 |
try: |
| 251 |
expiration = time.time() + lifetime |
| 252 |
answer = await self.resolve( |
| 253 |
dns._ddr._local_resolver_name, "svcb", lifetime=lifetime |
| 254 |
) |
| 255 |
timeout = dns.query._remaining(expiration) |
| 256 |
nameservers = await dns._ddr._get_nameservers_async(answer, timeout) |
| 257 |
if len(nameservers) > 0: |
| 258 |
self.nameservers = nameservers |
| 259 |
except Exception: |
| 260 |
pass |
| 261 |
|
| 262 |
|
| 263 |
default_resolver = None |
| 264 |
|
| 265 |
|
| 266 |
def get_default_resolver() -> Resolver: |
| 267 |
"""Get the default asynchronous resolver, initializing it if necessary.""" |
| 268 |
if default_resolver is None: |
| 269 |
reset_default_resolver() |
| 270 |
assert default_resolver is not None |
| 271 |
return default_resolver |
| 272 |
|
| 273 |
|
| 274 |
def reset_default_resolver() -> None: |
| 275 |
"""Re-initialize default asynchronous resolver. |
| 276 |
|
| 277 |
Note that the resolver configuration (i.e. /etc/resolv.conf on UNIX |
| 278 |
systems) will be re-read immediately. |
| 279 |
""" |
| 280 |
|
| 281 |
global default_resolver |
| 282 |
default_resolver = Resolver() |
| 283 |
|
| 284 |
|
| 285 |
async def resolve( |
| 286 |
qname: dns.name.Name | str, |
| 287 |
rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, |
| 288 |
rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, |
| 289 |
tcp: bool = False, |
| 290 |
source: str | None = None, |
| 291 |
raise_on_no_answer: bool = True, |
| 292 |
source_port: int = 0, |
| 293 |
lifetime: float | None = None, |
| 294 |
search: bool | None = None, |
| 295 |
backend: dns.asyncbackend.Backend | None = None, |
| 296 |
) -> dns.resolver.Answer: |
| 297 |
"""Query nameservers asynchronously to find the answer to the question. |
| 298 |
|
| 299 |
This is a convenience function that uses the default resolver |
| 300 |
object to make the query. |
| 301 |
|
| 302 |
See :py:func:`dns.asyncresolver.Resolver.resolve` for more |
| 303 |
information on the parameters. |
| 304 |
""" |
| 305 |
|
| 306 |
return await get_default_resolver().resolve( |
| 307 |
qname, |
| 308 |
rdtype, |
| 309 |
rdclass, |
| 310 |
tcp, |
| 311 |
source, |
| 312 |
raise_on_no_answer, |
| 313 |
source_port, |
| 314 |
lifetime, |
| 315 |
search, |
| 316 |
backend, |
| 317 |
) |
| 318 |
|
| 319 |
|
| 320 |
async def resolve_address( |
| 321 |
ipaddr: str, *args: Any, **kwargs: Any |
| 322 |
) -> dns.resolver.Answer: |
| 323 |
"""Use a resolver to run a reverse query for PTR records. |
| 324 |
|
| 325 |
See :py:func:`dns.asyncresolver.Resolver.resolve_address` for more |
| 326 |
information on the parameters. |
| 327 |
""" |
| 328 |
|
| 329 |
return await get_default_resolver().resolve_address(ipaddr, *args, **kwargs) |
| 330 |
|
| 331 |
|
| 332 |
async def resolve_name( |
| 333 |
name: dns.name.Name | str, family: int = socket.AF_UNSPEC, **kwargs: Any |
| 334 |
) -> dns.resolver.HostAnswers: |
| 335 |
"""Use a resolver to asynchronously query for address records. |
| 336 |
|
| 337 |
See :py:func:`dns.asyncresolver.Resolver.resolve_name` for more |
| 338 |
information on the parameters. |
| 339 |
""" |
| 340 |
|
| 341 |
return await get_default_resolver().resolve_name(name, family, **kwargs) |
| 342 |
|
| 343 |
|
| 344 |
async def canonical_name(name: dns.name.Name | str) -> dns.name.Name: |
| 345 |
"""Determine the canonical name of *name*. |
| 346 |
|
| 347 |
See :py:func:`dns.resolver.Resolver.canonical_name` for more |
| 348 |
information on the parameters and possible exceptions. |
| 349 |
""" |
| 350 |
|
| 351 |
return await get_default_resolver().canonical_name(name) |
| 352 |
|
| 353 |
|
| 354 |
async def try_ddr(timeout: float = 5.0) -> None: |
| 355 |
"""Try to update the default resolver's nameservers using Discovery of Designated |
| 356 |
Resolvers (DDR). If successful, the resolver will subsequently use |
| 357 |
DNS-over-HTTPS or DNS-over-TLS for future queries. |
| 358 |
|
| 359 |
See :py:func:`dns.resolver.Resolver.try_ddr` for more information. |
| 360 |
""" |
| 361 |
return await get_default_resolver().try_ddr(timeout) |
| 362 |
|
| 363 |
|
| 364 |
async def zone_for_name( |
| 365 |
name: dns.name.Name | str, |
| 366 |
rdclass: dns.rdataclass.RdataClass = dns.rdataclass.IN, |
| 367 |
tcp: bool = False, |
| 368 |
resolver: Resolver | None = None, |
| 369 |
backend: dns.asyncbackend.Backend | None = None, |
| 370 |
) -> dns.name.Name: |
| 371 |
"""Find the name of the zone which contains the specified name. |
| 372 |
|
| 373 |
See :py:func:`dns.resolver.Resolver.zone_for_name` for more |
| 374 |
information on the parameters and possible exceptions. |
| 375 |
""" |
| 376 |
|
| 377 |
if isinstance(name, str): |
| 378 |
name = dns.name.from_text(name, dns.name.root) |
| 379 |
if resolver is None: |
| 380 |
resolver = get_default_resolver() |
| 381 |
if not name.is_absolute(): |
| 382 |
raise NotAbsolute(name) |
| 383 |
while True: |
| 384 |
try: |
| 385 |
answer = await resolver.resolve( |
| 386 |
name, dns.rdatatype.SOA, rdclass, tcp, backend=backend |
| 387 |
) |
| 388 |
assert answer.rrset is not None |
| 389 |
if answer.rrset.name == name: |
| 390 |
return name |
| 391 |
# otherwise we were CNAMEd or DNAMEd and need to look higher |
| 392 |
except (NXDOMAIN, NoAnswer): |
| 393 |
pass |
| 394 |
try: |
| 395 |
name = name.parent() |
| 396 |
except dns.name.NoParent: # pragma: no cover |
| 397 |
raise NoRootSOA |
| 398 |
|
| 399 |
|
| 400 |
async def make_resolver_at( |
| 401 |
where: dns.name.Name | str, |
| 402 |
port: int = 53, |
| 403 |
family: int = socket.AF_UNSPEC, |
| 404 |
resolver: Resolver | None = None, |
| 405 |
) -> Resolver: |
| 406 |
"""Make a stub resolver using the specified destination as the full resolver. |
| 407 |
|
| 408 |
*where*, a ``dns.name.Name`` or ``str`` the domain name or IP address of the |
| 409 |
full resolver. |
| 410 |
|
| 411 |
*port*, an ``int``, the port to use. If not specified, the default is 53. |
| 412 |
|
| 413 |
*family*, an ``int``, the address family to use. This parameter is used if |
| 414 |
*where* is not an address. The default is ``socket.AF_UNSPEC`` in which case |
| 415 |
the first address returned by ``resolve_name()`` will be used, otherwise the |
| 416 |
first address of the specified family will be used. |
| 417 |
|
| 418 |
*resolver*, a ``dns.asyncresolver.Resolver`` or ``None``, the resolver to use for |
| 419 |
resolution of hostnames. If not specified, the default resolver will be used. |
| 420 |
|
| 421 |
Returns a ``dns.resolver.Resolver`` or raises an exception. |
| 422 |
""" |
| 423 |
if resolver is None: |
| 424 |
resolver = get_default_resolver() |
| 425 |
nameservers: List[str | dns.nameserver.Nameserver] = [] |
| 426 |
if isinstance(where, str) and dns.inet.is_address(where): |
| 427 |
nameservers.append(dns.nameserver.Do53Nameserver(where, port)) |
| 428 |
else: |
| 429 |
answers = await resolver.resolve_name(where, family) |
| 430 |
for address in answers.addresses(): |
| 431 |
nameservers.append(dns.nameserver.Do53Nameserver(address, port)) |
| 432 |
res = Resolver(configure=False) |
| 433 |
res.nameservers = nameservers |
| 434 |
return res |
| 435 |
|
| 436 |
|
| 437 |
async def resolve_at( |
| 438 |
where: dns.name.Name | str, |
| 439 |
qname: dns.name.Name | str, |
| 440 |
rdtype: dns.rdatatype.RdataType | str = dns.rdatatype.A, |
| 441 |
rdclass: dns.rdataclass.RdataClass | str = dns.rdataclass.IN, |
| 442 |
tcp: bool = False, |
| 443 |
source: str | None = None, |
| 444 |
raise_on_no_answer: bool = True, |
| 445 |
source_port: int = 0, |
| 446 |
lifetime: float | None = None, |
| 447 |
search: bool | None = None, |
| 448 |
backend: dns.asyncbackend.Backend | None = None, |
| 449 |
port: int = 53, |
| 450 |
family: int = socket.AF_UNSPEC, |
| 451 |
resolver: Resolver | None = None, |
| 452 |
) -> dns.resolver.Answer: |
| 453 |
"""Query nameservers to find the answer to the question. |
| 454 |
|
| 455 |
This is a convenience function that calls ``dns.asyncresolver.make_resolver_at()`` |
| 456 |
to make a resolver, and then uses it to resolve the query. |
| 457 |
|
| 458 |
See ``dns.asyncresolver.Resolver.resolve`` for more information on the resolution |
| 459 |
parameters, and ``dns.asyncresolver.make_resolver_at`` for information about the |
| 460 |
resolver parameters *where*, *port*, *family*, and *resolver*. |
| 461 |
|
| 462 |
If making more than one query, it is more efficient to call |
| 463 |
``dns.asyncresolver.make_resolver_at()`` and then use that resolver for the queries |
| 464 |
instead of calling ``resolve_at()`` multiple times. |
| 465 |
""" |
| 466 |
res = await make_resolver_at(where, port, family, resolver) |
| 467 |
return await res.resolve( |
| 468 |
qname, |
| 469 |
rdtype, |
| 470 |
rdclass, |
| 471 |
tcp, |
| 472 |
source, |
| 473 |
raise_on_no_answer, |
| 474 |
source_port, |
| 475 |
lifetime, |
| 476 |
search, |
| 477 |
backend, |
| 478 |
) |